Upload large files to Web API with Javascript

We can upload large files to a REST Web API with JavaScript using FormData. Below JavaScript code snippet uploads the file selected using a standard HTML file input tag.

//Change event for the html input tag
$("#inputUpload").change(function (fileupload) {
	var myXhr = $.ajaxSettings.xhr();

	//Creating Form Data to Submit
	var formData = new FormData();
	formData.append("fileToUpload", fileupload.currentTarget.files[0]);

	$.ajax({
		url: '/api/upload',
		type: 'POST',
		data: formData,
		cache: false,
		contentType: false,
		processData: false,
		xhr: function () {
			if (myXhr.upload) {
				myXhr.upload.addEventListener('progress', function (progress) {
					if (((progress.loaded / progress.total) * 100).toFixed() < 100) {
						//Notifiy upload progress percentage
						//((progress.loaded / progress.total) * 100).toFixed().toString()
					}
					else {
						//Upload complete
					}
				}, false);
			}
			return myXhr;
		}
	}).done(function (result) {
		//API call succeeded
	}).fail(function (xhr, status, error) { 
		// API call failed
		// Check the xhr.responseText (Use HTML Visualizer if you are in Visual Studio to find what's wrong)
		// If the request fails due to the request length exceeding maxAllowedContentLength, the error would be as below...
		// HTTP Error 404.13 - Not Found
		// The request filtering module is configured to deny a request that exceeds the request content length
	});
});

Update the maxAllowedContentLength in web.config as per the requirement. The below snippet shows the maxAllowedContentLength set to accept upto 2GB of data.

<system.webServer>
	<security>
		<requestFiltering>
			<requestLimits maxAllowedContentLength="2000000000" />
		</requestFiltering>
	</security>
</system.webServer>

Below code snippet is the ASP.NET Web API C# method that accepts the uploaded file

[HttpPost]
public HttpResponseMessage UploadFile()
{
	HttpResponseMessage result = null;
	try
	{
		var httpRequest = HttpContext.Current.Request;
		if (httpRequest.Files.Count != 0)
		{
			var uploadedFile = httpRequest.Files[0].FileName;
			var targetPath = "";
			var httpPostedFile = HttpContext.Current.Request.Files[0];
			var fileName = Path.GetFileName(httpPostedFile.FileName);
			if (httpPostedFile != null)
			{
				targetPath = Path.Combine(HttpContext.Current.Server.MapPath("~/uploadedFiles"), fileName);
				httpPostedFile.SaveAs(targetPath);
				result = new HttpResponseMessage(HttpStatusCode.OK);
			}
		}
		else
		{
			result = Request.CreateResponse(HttpStatusCode.BadRequest);
		}
	}
	catch (Exception ex)
	{
		result = Request.CreateResponse(HttpStatusCode.BadRequest);
	}
	return result;
}
Share This!

Leave a Reply

Your email address will not be published. Required fields are marked *