ASP. NET asynchronous Web API + jQuery Ajax file upload code analysis, jqueryajax
In this example, jquery ajax (web client) and async web api are used in double Asynchronization.
Jquery ajax post
1 $.ajax({ 2 type: "POST", 3 url: "/api/FileUpload", 4 contentType: false, 5 processData: false, 6 data: data, 7 success: function (results) { 8 ShowUploadControls(); 9 $("#uploadResults").empty();10 for (i = 0; i < results.length; i++) {11 $("#uploadResults").append($("<li/>").text(results[i]));12 }13 },14 error: function (xhr, ajaxOptions, thrownError) {15 ShowUploadControls();16 alert(xhr.responseText);17 }18 });
The client sends data in post mode. The callback script after successful upload is defined in success.
Async Web API
The return value of Action in Controller is Task <TResult>, which is defined in this example:
1 public Task<IEnumerable<string>> Post()2 {3 ... ... 4 }
The specific asynchronous effect is embodied in "File Content reading" and "subsequent processing.
1 string fullPath = HttpContext.Current.Server.MapPath("~/Uploads"); 2 CustomMultipartFormDataStreamProvider streamProvider = new CustomMultipartFormDataStreamProvider(fullPath); 3 var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t => 4 { 5 if (t.IsFaulted || t.IsCanceled) 6 throw new HttpResponseException(HttpStatusCode.InternalServerError); 7 8 var fileInfo = streamProvider.FileData.Select(i => 9 {10 var info = new FileInfo(i.LocalFileName);11 return "File saved as " + info.FullName + " (" + info.Length + ")";12 });13 return fileInfo;14 15 });
ReadAsMultipartAsync
(From MSDN) read all the body parts of the MIME multi-part message, and use the streamProvider instance to determine the write location of the content of each body part, and generate a set of HttpContent instances as the result.
Task. ContinueWith <TResult>
Create a continuation Task that is asynchronously executed when the target Task is completed. In this example, when the ReadAsMultipartAsync (read) task is completed, the behavior defined in ContinueWith will be executed asynchronously as a continuation.
MultipartFormDataStreamProvider object
An IMultipartStreamProvider is suitable for uploading HTML files to Write File Content to FileStream. The Stream provider checks the header field of <B> Content-Disposition </B> and determines whether the output Stream exists based on the <B> filename </B> parameter. If the <B> Content-Disposition </B> header field contains the <B> filename </B> parameter, the body part is written to FileStream. Otherwise, the body is written to MemoryStream. This makes it easier to process MIME multi-part HTML form data that is used as a combination of form data and file content.
TIPS: lambda expressions are reversed, from FileData to IEnumerable <string>
1 var fileInfo = streamProvider.FileData.Select(i =>2 {3 var info = new FileInfo(i.LocalFileName);4 return "File saved as " + info.FullName + " (" + info.Length + ")";5 });
Sample Code