Dropzone.js is a slick multi-file upload utility. A lot of times when uploading files we need to dynamically specify a query string parameter so that the uploads can be saved on the server at the correct path. Following example shows you how to do just that.
Front-end
<div class="jumbotron"> <form action="~/api/Upload" class="dropzone" enctype="multipart/form-data" id="dropzoneForm" method="post" name="dropzoneForm"> <div class="fallback"> <input multiple name="file" type="file"/> <input type="submit" value="Upload"/> </div> </form> </div> <style type="text/css"> .dz-max-files-reached { background-color: red; } </style> <script type = "text/javascript" > Dropzone.options.dropzoneForm = { maxFiles: 20, maxFilesize: 500, init: function() { this.on("processing", function(file) { // Customize the upload URL by adding querystring var baseUrl = $("#dropzoneForm").attr("action"); this.options.url = baseUrl + "?someParameter=someValue"; }); this.on("maxfilesexceeded", function(data) { var res = eval('(' + data.xhr.responseText + ')'); }); this.on("addedfile", function(file) { // Create the remove button var removeButton = Dropzone.createElement("<button>Remove file< \/button>"); // Capture the Dropzone instance as closure. var _this = this; // Listen to the click event removeButton.addEventListener("click", function(e) { // Make sure the button click doesn't submit the form: e.preventDefault(); e.stopPropagation(); // Remove the file preview. _this.removeFile(file); // If you want to the delete the file on the server as well, // you can do the AJAX request here. }); // Add the button to the file preview element. file.previewElement.appendChild(removeButton); }); } }; </script>
API
public class UploadController : ApiControllerBase { public async Task<IHttpActionResult> Post() { if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); try { var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); var baseUploadPath = @"D:\Uploads\" + Request.QueryString["someParameter"]; foreach (var file in provider.Contents) { if (file.Headers.ContentLength > 0) { var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); var filePath = Path.Combine(baseUploadPath, fileName); var buffer = await file.ReadAsByteArrayAsync(); File.WriteAllBytes(filePath, buffer); } } return Ok(); } catch (Exception ex) { var response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); throw new HttpResponseException(response); } } }
Code for this article can be downloaded from GitHub at bit.ly/web-api-file-upload-using-dropzone
The post Web API Multi-file Upload Using Dropzone.js appeared first on Software Rockstar.