ASP. NET WebAPi (selfhost) for file synchronization or asynchronous upload

Source: Internet
Author: User
Tags baseuri net serialization
Objective
Before we talked about the use of Angularjs upload to WEBAPI processing, while we in the MVC series of File upload, this article combined with MVC+WEBAPI to file synchronization or asynchronous upload, by the way review the CSS and JS,MVC as a client, Instead, WEBAPI uses IIS-independent Selfhost mode as the server to receive client-side files and its process is implemented with Ajax, let's take a look.

Simultaneous uploads

Needless to say, we look directly at the page.

<div class= "Container" > <div>  @if (viewbag.success! = null)  {   <div class= "alert Alert-danger "role=" alert ">    <strong> succeeded!</strong> successfully uploaded. <a href=" @ViewBag. Success "Target=" _ Blank ">open file</a>   </div>  }  else if (viewbag.failed! = null)  {   <div class=" Alert Alert-danger "role=" alert ">    <strong> failed!</strong> @ViewBag. Failed   </div>  } </div> @using (Html.BeginForm ("Syncupload", "Home", FormMethod.Post, new {role = "form", enctype = "Multipa Rt/form-data ", @style =" margin-top:50px; "})) {  <div class= "Form-group" >   <input type= "file" id= "file" name= "file"/>  </div>  <input type= "Submit" value= "Submit" class= "btn btn-primary"/>}</div>

The above we upload directly after uploading the status to display the view upload file path and access, it is so simple. Let's take the MVC background logic

[Httppost]public actionresult syncupload (httppostedfilebase file) {using (var client = new HttpClient ()) {using (var con Tent = new Multipartformdatacontent ()) {byte[] Bytes = new Byte[file.   Inputstream.length + 1]; File.   Inputstream.read (Bytes, 0, bytes.length);          var filecontent = new Bytearraycontent (Bytes); Set the attachment in the request header as the file name so that it can be obtained in webapi fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue ("attachment") {FileName = file.   FileName}; Content.   ADD (filecontent);   var requesturi = "Http://localhost:8084/api/upload/post"; var result = client. Postasync (RequestUri, content).   Result; if (result. StatusCode = = System.Net.HttpStatusCode.Created) {//Get to the upload file address and render to the view to access var m = result. Content.readasstringasync ().    Result;    var list = jsonconvert.deserializeobject<list<string>> (M); viewbag.success = list.    FirstOrDefault (); } else {viewbag.failed = "upload failed, status code:" + result. StatusCode + ", originalCause: "+ result. Reasonphrase + ", error message:" + result.   Content.tostring (); }}} return View ();}

Note: The above will get to the file byte stream array that needs to be passed to multipartformdatacontent, otherwise the file data will not be obtained when passed to Webapi.

The operation in MVC is complete so far, so let's take a look at what needs to be done in Webapi.

(1) First of all, it must be judged whether the uploaded data is mimetype type.

if (! Request.Content.IsMimeMultipartContent ()) {throw new httpresponseexception (Httpstatuscode.unsupportedmediatype);}

(2) We definitely need to regenerate a file name to avoid duplication, using GUIDs or date or other.

String name = Item. Headers.ContentDisposition.FileName.Replace ("\" "," "); string newfilename = Guid.NewGuid (). ToString ("N") + path.getextension (name);

(3) We need to use this type of Multipartfilestreamprovider to set the upload path and write the file into this.

var Provider = new Multipartfilestreamprovider (rootpath); var task = Request.Content.ReadAsMultipartAsync (provider) .....

(4) Return the upload file address.

Return Request.createresponse (httpstatuscode.created, Jsonconvert.serializeobject (Savedfilepath));
The steps are parsed so much that the assembly code is as follows:

Public task

Note: The above item. LocalFilename for E:\Documents\Visual Studio 2013\projects\webapireturnhtml\webapireturnhtml\upload\bodypart_ fa01ff79-4a5b-40f6-887f-ab514ec6636f, because we renamed the file name at this point, we need to move the file to our renamed file address.

The whole process is so simple, let's take a look at the demo results.

At this point, it is actually wrong, a bit intriguing, on the server is to return the following JSON string

list<string> Savedfilepath = new list<string> ();

At this point in the deserialization is actually an error, and then to see the error message on the page:

Unable to convert string to List<string> it's not one by one, okay, I'll see what the string is going to look like, "When you put the mouse on," Look at the following:

When I click to view the results are as follows:

The correct JSON is returned when the View button is clicked, and here we find that the json.net serialization is problematic, so the returned string needs to be processed into the correct JSON string for deserialization when it is deserialized and modified as follows:

var m = result. Content.readasstringasync (). Result;    m = M.trimstart (' \ "');    m = m.trimend (' \ "');    m = m.replace ("\ \", "");    var list = jsonconvert.deserializeobject<list<string>> (M);

Here our synchronous upload is over, this inside use json.net for deserialization when actually error problem, the first time encountered json.net deserialization problem, more wonderful, inexplicable.

Asynchronous upload

The so-called asynchronous upload is just using Ajax to upload, here is to review the script or Razor view, the following is only the view has been modified, for the asynchronous upload I take advantage of the asynchronous API in Jquery.form.js, see the following code:

<script src= "~/scripts/jquery-1.10.2.min.js" ></script><script src= "~/Scripts/jquery.form.js" > </script><script src= "~/scripts/bootstrap.min.js" ></script><link href= "~/Content/ Bootstrap.min.css "rel=" stylesheet "/> <div class=" container "style=" margin-top:30px "> <div id=" Success " Style= "Display:none;" > <div class= "alert Alert-danger" role= "alert" > <strong> upload successful </strong><span style= " margin-right:50px; " ></span><a href= "" target= "_blank" id= "linkaddr" > File access address </a> </div> </div> <div ID = "Fail" style= "Display:none;" > <div class= "alert Alert-danger" role= "alert" > <strong> upload failed </strong> </div> </div> & Lt;/div> @using (Ajax.beginform ("Asyncupload", "Home", new Ajaxoptions () {HttpMethod = "POST"}, new {enctype = "multi Part/form-data ", @style =" margin-top:10px; "})) {<div class= "Form-group" > <input type= "file" name= "file" id= "FU1"/> </div> <div class= "Form-group" > <input type= "Submit" class= "btn btn-primary" value= "Upload"/> </div >} <div class= "Form-group" > <div class= "Progress" id= "Progress" style= "Display:none;"  > <div class= "Progress-bar" >0%</div> </div> <div id= "status" ></div></div>  <style>. Progress {position:relative;  width:400px;  border:1px solid #ddd; padding:1px;  }. progress-bar {width:0px;  height:40px; Background-color: #57be65;  }</style> <script> (function () {var bar = $ ('. Progress-bar ');  var percent = $ ('. Progress-bar ');    $ (' form '). Ajaxform ({beforesend:function () {$ ("#progress"). Show ();    var percentvalue = ' 0% ';    Bar.width (Percentvalue);   Percent.html (Percentvalue);    }, Uploadprogress:function (event, Position, total, percentcomplete) {var percentvalue = percentcomplete + '% ';    Bar.width (Percentvalue);   Percent.html (Percentvalue); }, Success:function (d) {var Percentvalue = ' 100% ';    Bar.width (Percentvalue);    Percent.html (Percentvalue);   $ (' #fu1 '). Val (');     }, Complete:function (XHR) {if (Xhr.responsetext! = null) {$ ("#linkAddr"). Prop ("href", xhr.responsetext);    $ ("#success"). Show ();    } else {$ ("#fail"). Show (); }   }  }); }) ();</script>

Let's take a look at the upload process.

In the upload:

Upload complete:

Of course, the 100% here is only for small files in real-time upload, if the large file is definitely not real-time, using other components to achieve more suitable, here I just learn to learn this.

Note: Here again, before the MVC upload has been described, MVC default upload file is limited, so beyond its limit, you can not upload, you need to set the following

(1) In IIS 5 and IIS 6, the default file upload is a maximum of 4 megabytes, and when the uploaded file size exceeds 4 megabytes, you get an error message, but we set the file size by setting it down.

<system.web> 

(2) In IIS 7+, the default file upload is up to 28.6 megabytes, when the default size is exceeded, the same error message is obtained, but we can set the file upload size (as well as the above settings).

<system.webServer> <security>  <requestFiltering>   <requestlimits Maxallowedcontentlength= "2147483647"/>  </requestFiltering> </security></system.webserver >

Summarize

In this section we learned how to isolate MVC and webapi to upload, At the same time, we also found that there is a certain problem in deserialization, it is noted that when the one by one corresponding to the json.net returned JSON string is not a standard JSON string, we need to return the JSON string to do the following processing (perhaps there are other scenarios).

var jsonstring = "returned JSON string"; jsonstring = Jsonstring.trimstart (' \ "'); jsonstring = Jsonstring.trimend (' \" '); jsonstring = jsonstring.replace ("\ \", "");

The next step is to prepare the system for learning SQL Server and Oracle, incrementally, you say! Rest, rest!

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

  • Related Article

    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.