. Netcore implementing an example of uploading multiple files

Source: Internet
Author: User
This chapter is shared with all of you. Netcore MVC Framework Upload file example, the main content is: Form submission upload, Ajax upload, Ajax submission + upload progress effect, task Parallel processing +ajax submit + upload progress, very helpful to everyone, interested friends follow the small series to learn it

This chapter is shared with all of you. Netcore MVC Framework Upload file example, the main content is: Form submission upload, Ajax upload, Ajax submission + upload progress effect, task Parallel processing +ajax submit + upload progress, I believe when you read the article content can after good harvest, if you can wish to point a praise Because of yesterday's computer power, the content is not saved, this morning early to start the company from scratch, power outage this situation really makes people very headache ah, but for the community to share the environment, it is worthwhile, not many said to enter today's positive section of it;

Upload a group of images in form mode

First of all, let's look at the HTML code, here is the first simple to upload the file must be set in the form element inside the enctype= "Multipart/form-data" property and post, if you want to upload files, you need to file Type= ' The file ' element sets her property multiple= ' multiple ', so there is something like this:


<form class= "Form-horizontal" action= "/home/fileup" method= "post" enctype= "Multipart/form-data" >  < Input type= "file" Name= "Myphoto" class= "Form-control" multiple/> <br  />  <button class= "btn Btn-default ">form upload </button>  <br/>  <span style=" color:red "> @ViewData [" MsgBox "]< /SPAN>  </form>

Because of the form submission, this test case only uses the default type=submit of the button element to submit the form, and the code in the corresponding background action is as follows:


///<summary>//form Submit upload///</summary>//<param name= "user" ></  param>//<returns></returns> [HttpPost] public async task<iactionresult> fileup (MoUser user) {if (User. Myphoto = = NULL | | User. Myphoto.count <= 0) {MsgBox ("please upload the picture. "); return View ();  }//var file = Request.Form.Files; foreach (var file in user. Myphoto) {var fileName = file.  FileName; var contentType = file.  ContentType; var len = file.  Length;  var fileType = new string[] {"Image/jpeg", "Image/png"}; if (!filetype.any (b = b.contains (ContentType))) {MsgBox ($) can only upload {string. The picture in the format of Join (",", FileType)}. "); return View (); } if (Len > 1024x768 * 4) {MsgBox ("Upload image size can only be below 4M. "); return View ();  } var Path = Path.Combine (@ "D:\F\ learning \vs2017\netcore\netcore01\webapp01\wwwroot\myfile", fileName); using (var stream = System.IO.File.Create (path)) {await File.  Copytoasync (stream);  }} MsgBox ($ "upload succeeded"); return View (); }

The front-to-back action has to say that this form of form submission is quite straightforward, and it is important to note that the entity model used here corresponds to the uploaded file information, where the Mouser class is customized to public List<IFormFile> MyPhoto { get; set; } match the files type='file'的name in the HTML form via attributes. Property name name="MyPhoto" :


public class MoUser {public int UserId {get; set;} = 1, public string UserName {get; set;} = "God ox walk 3"; public list< Iformfile> Myphoto {get; set;}}

In this way, the uploaded file information can be stored in the Myphoto attribute of the custom Mouser class through the entity model;

Ajax uploads a set of images

Here we need to modify something in the HTML of the above example, no longer using the form submission, specifying the normal button to trigger the Ajax commit, complete HTML code such as:


<form class= "Form-horizontal" id= "FORM01" method= "post" enctype= "Multipart/form-data" >  <input type= " File "Name=" MyPhoto01 "class=" Form-control "multiple/> <br  />  <button type=" button "id=" Btnajax " class= "btn btn-default" >ajax upload </button>  <br/>  <span style= "color:red" id= "Span01" > </span>  </form>

With the layout, then take a look at the specific JS implementation code, here I use jquery Ajax submission method to operate, also used the HTML5 new Formdata to store the form's data:


$ ("#btnAjax"). On ("click", Function () {  var msg = $ ("#span01");  var form = document.getElementById ("form01");  Console.log (form);  var data = new FormData (form);  $.ajax ({  type: "POST",  URL: "/home/ajaxfileup",  data:data,  contenttype:false,  Processdata:false,  success:function (data) {   if (data) {   msg.html (data.msg);   }  },  Error:function () {   msg.html ("Upload file exception, please try again later!") ");  }  }); });

As for the background action method and example one, the key point is that I use the Request.Form.Files method directly to get all the uploaded files, no longer use the entity model, so the test cases more diverse:


<summary>//Ajax no Upload progress effect upload///</summary>//<returns></returns> [HttpPost] public Async Ta  Sk<jsonresult> Ajaxfileup () {var data = new Modata {Msg = "upload Failed"};  try {var files = Request.Form.Files.Where (b = = B.name = = "MyPhoto01"); Non-null limit if (files = = NULL | | files. Count () <= 0) {data. MSG = "Please select the uploaded file. "; return Json (data);  }//Format limit var allowtype = new string[] {"Image/jpeg", "Image/png"}; if (Files. Any (b =!allowtype.contains (B.contenttype))) {data. MSG = $ "can only upload {string. The file in the format of Join (",", Allowtype)}.   ";  return Json (data); }//Size limit if (files. Sum (b = b.length) >= * 1024x768 * 4) {data. MSG = "The total size of the uploaded file can only be below 4M." ";  return Json (data); }//write to Server disk foreach (var file in files) {var fileName = file.   FileName;   var path = Path.Combine (@ "D:\F\ learning \vs2017\netcore\netcore01\webapp01\wwwroot\myfile", fileName); using (var stream = System.IO.File.Create (path)) {await File.   Copytoasync (stream); }} data. MSG = "Upload success"; Data.  Status = 2; } catch (Exception ex) {data. MSG = ex.  Message; } return Json (data); }

If you have the patience to read here, then the content of the back of the personal feeling of your development will have a good help, do not bear your expectations;

Ajax Submission + Upload progress + a set of image uploads

We also first look at the corresponding HTML code, in fact, and example 2 almost the same, just change the name of the next:


<form class= "Form-horizontal" id= "form02" method= "post" enctype= "Multipart/form-data" >  <input type= " File "Name=" MyPhoto02 "class=" Form-control "multiple/> <br  />  <button type=" button "id=" btnAjax02 "class=" btn Btn-default ">ajax upload progress effect upload </button>  <br/> <span  style=" color:red " Id= "Span02" ></span>  </form>

To add a progress effect, you need to use the JS timer, time to get upload file upload progress data information, so here through the JS SetInterval method to request a progress data interface, note that after the use of this timer needs to be cleared, or continue to request your interface:


 $ ("#btnAjax02"). On ("click", Function () {var interbar;  var msg = $ ("#span02");  Msg.html ("Up Crossing, please later ...");  var form = document.getElementById ("form02");  Console.log (form);  var data = new FormData (form);  $.ajax ({type: "POST", url: "/home/ajaxfileup02", Data:data, Contenttype:false, Processdata:false, success:    function (data) {if (data) {msg.html (data.msg);   Clears the progress query if (Interbar) {clearinterval (Interbar);} }}, Error:function () {msg.html ("Upload file exception, please try again later!")   ");   if (Interbar) {clearinterval (Interbar);}  }  }); Get Progress Interbar = SetInterval (function () {$.post ("/home/progresbar02", function (data) {if (data) {var isclear    Val = true;    var strarr = [];    $.each (data, function (I, item) {Strarr.push (' file: ' + item.filename + ', current upload: "+ item.percentbar + ' <br/> ');    if (item.status! = 2) {isclearval = false;}    });    Msg.html (Strarr.join ("));    if (isclearval) {if (Interbar) {clearinterval (Interbar);}  }   } });  }, 200); });

Since the above mentioned the individual progress data interface, then we need to upload the action, but also the progress of the action, and this progress action to get the upload file data information must and upload the action has been, so need to use the cache and other ways to store data, Here I use the memorycache way, for already netcore only need to add component service in the starter file (for example: Startup.cs):


public void Configureservices (iservicecollection services)  {  //ADD framework services.  Services. Addmvc ();   Add cache support  services. Adddistributedmemorycache (); }

The constructor is then injected into the corresponding interface controller:


  ReadOnly IMemoryCache _cache; Public HomeController (ioptions<mooptions> options, ilogger

Here we can use the cache to store our upload progress information and see the action to process the upload:


private string CacheKey = "Userid_upfile"; private string cacheKey03 = "Userid_upfile03"; <summary>///Ajax Upload Progress effect upload///</summary>//<returns></returns> [HttpPost] public Async Tas  K<jsonresult> AjaxFileUp02 () {var data = new Modata {Msg = "upload Failed"};  try {var files = Request.Form.Files.Where (b = = B.name = = "MyPhoto02"); Non-null limit if (files = = NULL | | files. Count () <= 0) {data. MSG = "Please select the uploaded file. "; return Json (data);  }//Format limit var allowtype = new string[] {"Image/jpeg", "Image/png"}; if (Files. Any (b =!allowtype.contains (B.contenttype))) {data. MSG = $ "can only upload {string. The file in the format of Join (",", Allowtype)}.   ";  return Json (data); }//Size limit if (files. Sum (b = b.length) >= * 1024x768 * 4) {data. MSG = "The total size of the uploaded file can only be below 4M." ";  return Json (data);  }//Initialize the bar to upload multiple files and store them in cache for easy upload progress var listbar = new list<mobar> (); Files. ToList (). ForEach (b = = {Listbar.add (new MoBar {FileName = b.filename, Status = 1, Currbar = 0, TotalbAR = b.length});  }); _cache.  Set<list<mobar>> (CacheKey, Listbar); Write to Server disk foreach (var file in files) {//Total size var totalsize = file.   Length;   Initialize the size of each read var readsize = 1024L;   var bt = new Byte[totalsize > readsize readsize:totalsize];   The size currently read var currentsize = 0L; var fileName = file.   FileName;   var path = Path.Combine (@ "D:\F\ learning \vs2017\netcore\netcore01\webapp01\wwwroot\myfile", fileName); using (var stream = System.IO.File.Create (path)) {//await File.   Copytoasync (stream); Progress bar processing process using (var InputStream = file. Openreadstream ()) {//read upload file stream while (await Inputstream.readasync (BT, 0, Bt. Length) > 0) {//current read currentsize + = BT.    Length; Writes the upload stream to the server file in await stream. WriteAsync (BT, 0, Bt.    Length);     Gets the size of each read ReadSize = currentsize + readsize <= totalsize?    Readsize:totalsize-currentsize;    Reset BT = new Byte[readsize]; Set the current uploaded file progress and re-cache to the progress cache var bars = _cache. Get<list<    Mobar>> (CacheKey); var Currbar = bars. Where (b = b.filename = = FileName).    Singleordefault ();    Currbar.currbar = CurrentSize; Currbar.status = CurrentSize >= totalsize?    2:1; _cache.    Set<list<mobar>> (CacheKey, bars);    System.Threading.Thread.Sleep (1000 * 1); }}} data.  MSG = "Upload complete"; Data.  Status = 2; } catch (Exception ex) {data. MSG = ex.  Message; } return Json (data); }

Code suddenly become more, in fact, in accordance with the logic to increase the storage progress of the cache, and read the logic of the upload file stream, specific people can carefully look at the code, there are notes, and then it is the progress of the Information action interface:


[HttpPost]  Public Jsonresult ProgresBar02 ()  {   var bars = new list<mobar> ();   Try   {    bars = _cache. Get<list<mobar>> (CacheKey);   }   catch (Exception ex)   {   }   return Json (bars);  }

The progress interface only needs to get the progress information in the cache, note: Here is the test case, the specific use of the scene please add other logic code, the following to see the effect:

Task Parallel Processing +ajax commit + upload progress + a set of image uploads

This section will use task to process the uploaded file, it can be seen in the previous section, if you upload multiple files, then all in the order of a read file stream to generate upload files to the server, here to improve the use of task features, you can read different file streams simultaneously, First look at the HTML code and JS code:


<form class= "Form-horizontal" id= "form03" method= "post" enctype= "Multipart/form-data" >    <input type= " File "Name=" MyPhoto03 "class=" Form-control "multiple/> <br    />    <button type=" button "id=" btnAjax03 "class=" btn Btn-default ">task task processing Ajax upload Progress effect upload </button> <br/> <span style=    " Color:red "id=" span03 "></span>   </form>

Since the JS code with example 3 is no different here I directly post the code:


$ ("#btnAjax03"). On ("click", Function () {var interbar;   var msg = $ ("#span03");   Msg.html ("Up Crossing, please later ...");   var form = document.getElementById ("form03");   Console.log (form);   var data = new FormData (form); $.ajax ({type: "POST", url: "/HOME/AJAXFILEUP03", Data:data, Contenttype:false, Processdata:false, Su      Ccess:function (data) {if (data) {msg.html (data.msg);     Clears the progress query if (Interbar) {clearinterval (Interbar);} }}, Error:function () {msg.html ("Upload file exception, please try again later!")     ");    if (Interbar) {clearinterval (Interbar);}   }   }); Get Progress Interbar = SetInterval (function () {$.post ("/home/progresbar03", function (data) {if (data) {var i      Sclearval = true;      var strarr = [];       $.each (data, function (I, item) {Strarr.push (' file: ' + item.filename + ', current upload: "+ item.percentbar + ' <br/> ');      if (item.status! = 2) {isclearval = false;}      });      Msg.html (Strarr.join ("));    if (isclearval) {   if (Interbar) {clearinterval (Interbar);}   }     }    });  }, 200); });

Key points in the background, the task array to store the processing tasks for each uploaded file task[] tasks = new Task[len]; , and then use Task.waitall (tasks); Wait for all upload tasks to complete, here is a special note that you must wait here, or you will lose the upload file stream (multiple test results):


<summary>///Ajax Upload Progress effect upload///</summary>//<returns></returns> [HttpPost] public Jsonr   Esult AjaxFileUp03 () {var data = new Modata {Msg = "upload Failed"};    try {var files = Request.Form.Files.Where (b = = B.name = = "MyPhoto03"); Non-null limit if (files = = NULL | | files. Count () <= 0) {data. MSG = "Please select the uploaded file. "; return Json (data);    }//Format limit var allowtype = new string[] {"Image/jpeg", "Image/png"}; if (Files. Any (b =!allowtype.contains (B.contenttype))) {data. MSG = $ "can only upload {string. The file in the format of Join (",", Allowtype)}.     ";    return Json (data); }//Size limit if (files. Sum (b = b.length) >= * 1024x768 * 4) {data. MSG = "The total size of the uploaded file can only be below 4M." ";    return Json (data);    }//Initialize the bar to upload multiple files and store them in cache for easy upload progress var listbar = new list<mobar> (); Files. ToList (). ForEach (b = = {Listbar.add (new MoBar {FileName = b.filename, Status = 1, Currbar = 0, T    Otalbar = b.length});    }); _cache. Set<    List<mobar>> (cacheKey03, Listbar); var len = files.    Count ();    task[] tasks = new Task[len]; Write to server disk for (int i = 0; i < len; i++) {var file = files. Skip (i). Take (1).     Singleordefault ();      Tasks[i] = Task.Factory.StartNew ((p) = = {var item = p as Iformfile; Total size var totalsize = Item.      Length;      Initialize the size of each read var readsize = 1024L;      var bt = new Byte[totalsize > readsize readsize:totalsize];      The size currently read var currentsize = 0L; var fileName = Item.      FileName;      var path = Path.Combine (@ "D:\F\ learning \vs2017\netcore\netcore01\webapp01\wwwroot\myfile", fileName); using (var stream = System.IO.File.Create (path)) {//progress bar processing process using (var InputStream = Item. Openreadstream ()) {//read upload file stream while (Inputstream.read (BT, 0, Bt. Length) > 0) {//current read currentsize + = BT.         Length; Writes the upload stream to the server file in stream. Write (BT, 0, Bt.         Length);  Gets the size of each read       ReadSize = currentsize + readsize <= totalsize?         Readsize:totalsize-currentsize;         Reset BT = new Byte[readsize]; Set the current uploaded file progress and re-cache to the progress cache var bars = _cache.         Get<list<mobar>> (CACHEKEY03); var Currbar = bars. Where (b = b.filename = = FileName).         Singleordefault ();         Currbar.currbar = CurrentSize; Currbar.status = CurrentSize >= totalsize?         2:1; _cache.         Set<list<mobar>> (cacheKey03, bars);        System.Threading.Thread.Sleep (1000 * 1);    }}}}, file);    }//Task Wait, here must wait, otherwise you will lose the upload file stream Task.waitall (tasks); Data.    MSG = "Upload complete"; Data.   Status = 2; } catch (Exception ex) {data. MSG = ex.   Message;  } return Json (data); }

The action to get the upload progress is simply to read the cached data:


[HttpPost]  Public Jsonresult ProgresBar03 ()  {   var bars = new list<mobar> ();   Try   {    bars = _cache. Get<list<mobar>> (cacheKey03);   }   catch (Exception ex)   {   }   return Json (bars);  }

Here is an entity class for uploading progress:


public class Modata {//<summary>//  0: Failure 1: Upload 2: Success///  </summary> public  int Status {get ; Set Public  string MSG {get, set;}} public class Mobar:modata {//<summary>///  file name///  </SU Mmary> public  string FileName {get; set;}  <summary>///  current upload size///  </summary> public  long Currbar {get; set;}  <summary>///Total size///  </summary> public  long Totalbar {get; set;}  <summary>///progress Percentage///  </summary> public  string Percentbar  {   get   {    return $ "{(this. Currbar * 100/this. Totalbar)}% ";   }  } }

The way to handle uploading files to this task is done, so let's look at the results:

Can be compared by example 3 and 4, not using the task and the effect of the difference, so that the effect you deserve to have, patience to read the content of the friend, did not let you down, if you can may wish to point a "like" or sweep a code to support the author, thank you; the content finally attached to the specific test case code:. Netcore Several examples of uploading multiple files

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.