Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Web API Multi-file Upload Using Dropzone.js Specifying Dynamic Query String
<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>
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);
}
}
}
@softwarerockstar

This comment has been minimized.

Copy link
Owner Author

softwarerockstar commented Apr 25, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.