Tuesday, December 9, 2014

ASP.NET MVC File Upload through jQuery AJAX

HTML:
<input type="file" name="file" id="file" />

Javascript Submit:
var formData = new FormData();
var file = $("#file")[0].files[0];
formData.append("file", file);
formData.append("SourceId", 1234);
ajaxRequestFormData(window.urls.uploadAttachment, formData)

jQuery AJAX:
ajaxRequestFormData = function (url, model) {
$.ajax({
url: url,
type: "POST",
cache: false,
data: model,
dataType: "json",
contentType: false,
processData: false,
beforeSend: showProgress()
}).done(function (data) {
...
hideProgress();
}).fail(function () {
...
});
};

Controller Action:
public virtual ActionResult UploadAttachment(AttachmentDto attachment)
{
var file = Request.Files[0];
attachment.File = file;

var sourceId = attachment.SourceId;

...
}

Domain Class:
public class AttachmentDto
{
public HttpPostedFileBase File { get; set; }
public decimal SourceId { get; set; }
...
}

No comments: