Skip to main content

Drag and drop image upload in an ASP.NET Core editor

The editor with a picture in the text

People expect to drag a picture from the desktop straight into what they are writing. In RichTextBox this needs no extra code: once the upload endpoint is mapped, dropping a picture uploads it and inserts it where it lands.

What you need

// Program.cs
app.MapRichTextBoxUploads();

<!-- the page -->
<richtextbox name="Body" toolbar="default" height="400px"></richtextbox>

There is no button to add and no setting to turn on. Pasting a picture from the clipboard takes the same path.

What happens to the file

A dropped picture is treated exactly like one chosen with the Insert Image button:

  1. The editor sends it to /richtextbox/upload.
  2. The server checks the extension, size and real file type, and removes GPS and camera data.
  3. The store saves it, and the returned address goes into the text.

Dropping is therefore no back door around your rules. A file the server refuses is not stored.

Limits to think about

Phones and modern cameras produce large files. The default limit is 4 MB, which many phone photos exceed. If people tell you their photos fail, raise it for images only:

builder.Services.AddRichTextBox(options =>
{
    options.MaxUploadBytesByExtension[".jpg"] = 12 * 1024 * 1024;
    options.MaxUploadBytesByExtension[".jpeg"] = 12 * 1024 * 1024;
});

Your web server has its own limit as well. IIS refuses requests over about 30 MB by default, whatever the option says.

Who can drop files

The drop calls the same endpoint as everything else, so your authorization policy applies. A user who may not upload gets a refusal rather than a stored file.

Read next