ASP. NET asynchronous Web API + jQuery Ajax File upload Code small analysis

Source: Internet
Author: User

The example actually applies the jquery Ajax (Web Client) + Async Web API to double-async.

jquery Ajax Post

1 $.ajax ({2Type: "POST",3URL: "/api/fileupload",4ContentType:false,5ProcessData:false,6 Data:data,7Successfunction(results) {8 showuploadcontrols ();9$ ("#uploadResults"). empty ();Ten          for(i = 0; i < results.length; i++) { One$ ("#uploadResults"). Append ($ ("<li/>")). Text (results[i])); A         } -     }, -Errorfunction(XHR, ajaxoptions, thrownerror) { the showuploadcontrols (); - alert (xhr.responsetext); -     } -});

The client sends the data as a post. The callback script is defined at success where the upload succeeds.

Async Web API

The controller action return value is task<tresult> In this case, it is defined as follows:

1  Public task<ienumerable<string>> Post ()2{3     ...        4 }

and the specific asynchronous effect is embodied in "file content read" and "Follow-up processing".

1 stringFullPath = HttpContext.Current.Server.MapPath ("~/uploads");2Custommultipartformdatastreamprovider Streamprovider =NewCustommultipartformdatastreamprovider (fullPath);3 varTask = Request.Content.ReadAsMultipartAsync (Streamprovider). ContinueWith (t =4 {5     if(t.isfaulted | |t.iscanceled)6         Throw Newhttpresponseexception (httpstatuscode.internalservererror);7 8     varFileInfo = StreamProvider.FileData.Select (i =9     {Ten         varinfo =NewFileInfo (i.localfilename); One         return "File saved as"+ info. FullName +" ("+ info. Length +")"; A     }); -     returnFileInfo; -  the});

Readasmultipartasync

(from MSDN) reads all the body parts of a MIME multipart message and generates a set of httpcontent instances as a result by using the Streamprovider instance to determine where each body part of the content is written.


Task.continuewith<tresult>

Creates a continuation task that executes asynchronously when the target Task completes. Specifically, in this example, when the Readasmultipartasync (read) task finishes, the behavior defined in ContinueWith is executed asynchronously as a continuation.

Multipartformdatastreamprovider Object

A imultipartstreamprovider that is suitable for use with HTML file uploads to write file contents to FileStream. The stream provider will view the <b>Content-Disposition</b> header field and determine the output stream based on whether the <b>filename</b> parameter exists. If the <b>filename</b> parameter is present in the <b>Content-Disposition</b> header field, the body part is written to FileStream, otherwise the body part is written The MemoryStream. This makes it easier to handle MIME multipart HTML form data as a combination of form data and file content.

tips: lambda expression inversion, from filedata to ienumerable<string>

1 var fileInfo = streamProvider.FileData.Select (i =2{3     var ) New  FileInfo (i.localfilename); 4     return " "" ("")"; 5 });

Sample code

ASP. NET asynchronous Web API + jQuery Ajax File upload Code small analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.