Featured

Upload Files by Drag And Drop Using Dropzone.JS in ASP.NET 5

Last modified: June 16, 2021
Step 1

Create an ASP.NET Core MVC application.

Step 2

Go to https://www.dropzonejs.com/ and download the dropzone file. Create a folder called dropzonejs in wwwroot/lib folder and copy the dropzone.css and dropzone.js into it. In Home's Index View, link the JavaScript and CSS files as below.

<script src="~/lib/dropzonejs/dropzone.js"></script> <link href="~/lib/dropzonejs/dropzone.css" rel="stylesheet" />
Step 3

We need to put a placeholder for drag and drop dropzonejs. To do so, we do as below. The important is that we put class name dropzone to the form. The form submit to /Home/Upload method.

<div class="row"> <div class="col-md-9"> <div id="dropzone"> <form action="/Home/Upload" class="dropzone needsclick dz-clickable" id="uploader"> <div class="dz-message needsclick"> Drop files here or click to upload.<br> </div> </form> </div> </div> </div>
Step 4

In the Home controller, we add a new method called upload. We received the file (submit by form) in the form of IFormFile. We set the upload path to "C:\Temp", you can set anything you like as long there is correct permission to upload files. We then check if the file has content by checking it length. CopyToAsync copies the file stream to a file and saves it to the destination.

[HttpPost] public async Task<IActionResult> Upload(IFormFile file) { var uploads = @"C:\Temp\"; if (file.Length > 0) { using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create)) { await file.CopyToAsync(fileStream); } } return RedirectToAction("Index"); }