I am uploading a file asynchronously with HTML5 in MVC3. If I have a large file, say 1GB in size, and after 50% upload completion I cancel the upload or close the browser, it still saves a 500MB file within the target folder.
How can I handle this problem within the controller and on the client side?
Here is my controller action:
[HttpPost]
public ActionResult Upload(object fileToUpload1)
{
var fileName = Request.Headers["X-File-Name"];
var fileSize = Request.Headers["X-File-Size"];
var fileType = Request.Headers["X-File-Type"];
Request.SaveAs("D:\\uploadimage\\" + fileName, false);
if (fileToUpload1 == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else { return Json(false, JsonRequestBehavior.AllowGet); }
// return Json(false, JsonRequestBehavior.AllowGet);
}
And here is the Javascript:
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", uploadProgress, false);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
//assign value to prgress bar Div
var progressBar = document.getElementById("progressBar");
progressBar.max = evt.total;
progressBar.value = evt.loaded;
}
}
// File load event
xhr.upload.addEventListener("load", loadSuccess, false);
function loadSuccess(evt) {
$(fileParentDivobj).find(".ImgDiv").find("span").html("uploaded");
addfile(fileParentDivobj);
}
//handling error
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
xhr.open("POST", "@Url.Action("Upload","Home")", true);
// Set appropriate headers
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.setRequestHeader("X-File", file);
// Send the file (doh)
xhr.send(file);