Skip to main content

Attach PDF and Word files in an ASP.NET Core rich text editor

The Insert Document dialog over the editor

A price list, a form or a contract often belongs in the article as a file people can download. The Insert Document button uploads a file and inserts a link to it.

Add the button

It is in the default and full toolbars. In your own toolbar, its name is insertdocument:

<richtextbox name="Body"
             toolbar="{insertdocument}|{bold,italic}|{undo,redo}"
             height="300px"></richtextbox>

Which files are allowed

The default list for files is: zip, rar, pdf, doc, docx, xls, xlsx, rtf, txt, mp4 and mp3. Change it through the options:

builder.Services.AddRichTextBox(options =>
{
    options.AllowedFileExtensions.Remove(".rar");
    options.AllowedFileExtensions.Add(".csv");
    options.MaxUploadBytesByExtension[".pdf"] = 50 * 1024 * 1024;   // 50 MB PDFs, 4 MB for the rest
});

Think before you add a type. Never add anything your web server can run, such as .aspx or .cshtml, and leave out .html, .svg and .js, which a browser would run as part of your site.

What is checked

The extension must be on the list and the size within the limit. Where the package knows a format's signature, the first bytes must match it too, so a program renamed report.pdf is refused. Word and Excel files are containers and contain whatever people put in them, so they are not inspected inside.

If your users exchange files with the public, treat them as you would an e-mail attachment. Register an IUploadValidator if you want your own check as well, such as a virus scanner. It runs before the store saves the file.

Confidential files

A link to a file in wwwroot/uploads works for anyone who has it. For documents only certain people should read, keep them out of wwwroot, and serve them through an action that checks access first.

Read next