In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
This chapter shares with you an example of uploading files in the .NetCore MVC framework. The main contents are: form submission upload, ajax upload, ajax submission + upload progress effect, Task parallel processing + ajax submission + upload progress. I believe you can get a good harvest after reading the article, if you can like it. As the computer ran out of power yesterday, and the content that was about to be finished was not saved, it was mentioned this morning that the company would start all over again. The situation of power outage is really a headache, but it is also worth it for the sharing environment of the community. Say no more to get into today's main article.
Upload a group of pictures in form mode
First, let's take a look at our html code. Here, to upload a file, you must set the enctype= "multipart/form-data" attribute and post method in the form element. If you want to upload files with multiple options, you need to set the file type='file' element to her attribute multiple='multiple', so you have the following:
Form upload @ ViewData ["MsgBox"]
Due to form submission, this test case only uses the default type=submit of the button element to submit the form, and the corresponding code in the background Action is as follows:
/ [HttpPost] public async Task FileUp (MoUser user) {if (user.MyPhoto = = null | | user.MyPhoto.Count b.Contains (contentType)) {MsgBox ($"can only upload pictures in {string.Join (", ", fileType)} format.") ; return View ();} if (len > 1024 * 1024 * 4) {MsgBox ("upload image size can only be less than 4m.") ; return View ();} var path = Path.Combine (@ "D:\ F\ learn\ vs2017\ netcore\ netcore01\ WebApp01\ wwwroot\ myfile", fileName); using (var stream = System.IO.File.Create (path)) {await file.CopyToAsync (stream) }} MsgBox ($"upload successful"); return View ();}
Action from the front end to the back end has to say that this form form submission method is quite simple. It should be noted that the entity model method used by Action here corresponds to the uploaded file information. Here, the MoUser class is customized, and the attribute public List MyPhoto {get; set;} is used to match the name attribute name name= "MyPhoto" of the file type='file' in the html form:
Public class MoUser {public int UserId {get; set;} = 1; public string UserName {get; set;} = "Shenniu Walk 3"; public List MyPhoto {get; set;}}
In this way, the uploaded file information can be stored in the MyPhoto attribute in the custom MoUser class in the way of the entity model.
Ajax uploads a group of pictures
Here, you need to modify something at html in the above example. Instead of using form submission, specify a normal button button to trigger the submission of ajax. The complete html code is as follows:
Ajax upload
With the layout, let's take a look at the specific js implementation code. Here I use the ajax submission method of jquery and the new FormData of html5 to store the data of the form:
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 is abnormal, please try again later!") ;}})
As for the method of backend Action is not much different from that of example 1, the key point is that I directly use Request.Form.Files to get all the uploaded files, instead of using physical model, so the test cases are more diversified:
/ ajax has no upload progress effect upload / [HttpPost] public async Task AjaxFileUp () {var data = new MoData {Msg = "upload failed"}; try {var files = Request.Form.Files.Where (b = > b.Name = = "MyPhoto01") / / non-empty restriction if (files = = null | | files.Count ()! allowType.Contains (b.ContentType)) {data.Msg = $"only files in {string.Join (", ", allowType)} format can be uploaded." ; return Json (data);} / / size limit if (files.Sum (b = > b.Length) > = 1024 * 1024 * 4) {data.Msg = "the total size of uploaded files can only be less than 4m." ; return Json (data);} / / write to the server disk foreach (var file in files) {var fileName = file.FileName; var path = Path.Combine (@ "D:\ F\ learn\ vs2017\ netcore\ netcore01\ WebApp01\ wwwroot\ myfile", fileName) Using (var stream = System.IO.File.Create (path)) {await file.CopyToAsync (stream);}} data.Msg = "uploaded successfully"; data.Status = 2 } catch (Exception ex) {data.Msg = ex.Message;} return Json (data);}
If you have the patience to read this, then the following content will be helpful to your development and live up to your expectations.
Ajax submission + upload progress + upload of a group of images
Similarly, let's first take a look at the corresponding html code, which is almost the same as example 2, except that the name has been changed:
Ajax upload progress effect upload
To add a progress effect, you need to use the timer of js to regularly obtain the upload progress data information of uploaded files. Therefore, you can regularly request a progress data API through js's setInterval method. Note that you need to clear this timer after you finish using it, or you will keep asking for the API:
On ("click", function () {var interBar; var msg = $("# span02"); msg.html ("uploading, please wait a moment"); 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) / / clear progress query if (interBar) {clearInterval (interBar);}, error: function () {msg.html ("upload file is abnormal, please try again later!") ; if (interBar) {clearInterval (interBar);}) / / get progress interBar = setInterval (function () {$.post ("/ home/ProgresBar02", function (data) {if (data) {var isClearVal = true; var strArr = [] $.each (data, function (I, item) {strArr.push ('File:' + item.fileName + ", current upload:" + item.percentBar +'); if (item.status! = 2) {isClearVal = false;}}) Msg.html (strArr.join (''); if (isClearVal) {if (interBar) {clearInterval (interBar);}});})
Since a separate progress data API is mentioned above, in addition to uploading the Action, we also need the progress Action, and the data information of the uploaded file obtained by the progress Action must be consistent with the uploaded Action, so we need to use cache and other data storage methods. Here I use the MemoryCache method. For already netcore, you only need to add component services to the starting file (such as Startup.cs):
Public void ConfigureServices (IServiceCollection services) {/ / Add framework services. Services.AddMvc (); / / add cache to support services.AddDistributedMemoryCache ();}
Then inject it into the corresponding interface Controller through the constructor:
Readonly IMemoryCache _ cache; public HomeController (IOptions options, ILogger logger, IMemoryCache cache) {this._options = options.Value; _ logger = logger; _ cache = cache;}
At this point, we can use cache to store our upload progress information. Let's take a look at the Action for processing uploads:
Private string cacheKey = "UserId_UpFile"; private string cacheKey03 = "UserId_UpFile03"; / ajax upload progress effect upload / [HttpPost] public async Task AjaxFileUp02 () {var data = new MoData {Msg = "upload failed"} Try {var files = Request.Form.Files.Where (b = > b.Name = = "MyPhoto02") / / non-empty restriction if (files = = null | | files.Count ()! allowType.Contains (b.ContentType)) {data.Msg = $"only files in {string.Join (", ", allowType)} format can be uploaded." ; return Json (data);} / / size limit if (files.Sum (b = > b.Length) > = 1024 * 1024 * 4) {data.Msg = "the total size of uploaded files can only be less than 4m." ; return Json (data);} / / initialize the Bar for uploading multiple files and store it in the cache to get the upload progress var listBar = new List () Files.ToList () .ForEach (b = > {listBar.Add (new MoBar {FileName = b.FileName, Status = 1, CurrBar = 0) TotalBar = b.Length}) }); _ cache.Set (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]; / / currently read size var currentSize = 0L; var fileName = file.FileName; var path = Path.Combine (@ "D:\ F\ learn\ vs2017\ netcore\ netcore01\ WebApp01\ wwwroot\ myfile", fileName) Using (var stream = System.IO.File.Create (path)) {/ / await file.CopyToAsync (stream) / / Progress bar processing flow using (var inputStream = file.OpenReadStream ()) {/ / read upload file stream while (await inputStream.ReadAsync (bt, 0) Bt.Length) > 0) {/ / the length of current read currentSize + = bt.Length / / write the upload stream to the server file await stream.WriteAsync (bt, 0, bt.Length); / / get the size of each read readSize = currentSize + readSize b.FileName = = fileName) .SingleOrDefault () CurrBar.CurrBar = currentSize; currBar.Status = currentSize > = totalSize? 2: 1; _ cache.Set (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);}
The code suddenly becomes more and more. In fact, logically speaking, it increases the Cache of the storage progress and the logic of reading the uploaded file stream one by one. For details, you can take a closer look at the code, all of which are described in notes. Next is our progress information Action API:
[HttpPost] public JsonResult ProgresBar02 () {var bars = new List (); try {bars = _ cache.Get (cacheKey);} catch (Exception ex) {} return Json (bars);}
The progress API only needs to obtain the progress information in the cache. Note: here are the test cases. For specific usage scenarios, please add other logic codes. Let's take a look at the screenshot of the effect:
Task parallel processing + ajax submission + upload progress + upload of a group of images
In this section, Task will be used to process uploaded files. As can be seen from the screenshot in the previous section, if you upload multiple files, you will read the file stream one by one in order to generate the uploaded file to the server. Here, we can make use of the characteristics of Task to read different file streams at the same time. Let's take a look at html code and js code:
Task task processing ajax upload progress effect upload
Since it is no different from the js code in example 3, I will post the code directly here:
On ("click", function () {var interBar; var msg = $("# span03"); msg.html ("uploading, please wait a moment"); 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 Success: function (data) {if (data) {msg.html (data.msg) / / clear progress query if (interBar) {clearInterval (interBar);}, error: function () {msg.html ("upload file is abnormal, please try again later!") ; if (interBar) {clearInterval (interBar);}); / / get progress interBar = setInterval (function () {$.post ("/ home/ProgresBar03", function (data) {if (data) {var isClearVal = true) Var strArr = []; $.each (data, function (I, item) {strArr.push ('File:' + item.fileName + ", current upload:" + item.percentBar +''); if (item.status! = 2) {isClearVal = false }}); msg.html (strArr.join (')); if (isClearVal) {if (interBar) {clearInterval (interBar);}}) }, 200);)
The key point is in the background. The processing task of each uploaded file Task [] tasks = new Task [len]; is stored through the task array, and then Task.WaitAll (tasks) is used. Wait for the completion of all upload tasks. Please note that you must wait here, otherwise the uploaded file stream will be lost (multiple test results):
/ ajax upload progress effect upload / [HttpPost] public JsonResult AjaxFileUp03 () {var data = new MoData {Msg = "upload failed"}; try {var files = Request.Form.Files.Where (b = > b.Name = = "MyPhoto03") / / non-empty restriction if (files = = null | | files.Count ()! allowType.Contains (b.ContentType)) {data.Msg = $"only files in {string.Join (", ", allowType)} format can be uploaded." ; return Json (data);} / / size limit if (files.Sum (b = > b.Length) > = 1024 * 1024 * 4) {data.Msg = "the total size of uploaded files can only be less than 4m." ; return Json (data);} / / initialize the Bar for uploading multiple files and store it in the cache to get the upload progress var listBar = new List () Files.ToList () .ForEach (b = > {listBar.Add (new MoBar {FileName = b.FileName, Status = 1, CurrBar = 0) TotalBar = b.Length}) }); _ cache.Set (cacheKey03, listBar); var len = files.Count (); Task [] tasks = new Task [len]; / / write to the 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]; / / currently read size var currentSize = 0L; var fileName = item.FileName; var path = Path.Combine (@ "D:\ F\ learn\ vs2017\ netcore\ netcore01\ WebApp01\ wwwroot\ myfile", fileName) Using (var stream = System.IO.File.Create (path)) {/ / Progress Bar processing flow using (var inputStream = item.OpenReadStream ()) { / / read upload file stream while (inputStream.Read (bt) 0, bt.Length) > 0) {/ / the length of current read currentSize + = bt.Length / / write the upload stream to the server file stream.Write (bt, 0, bt.Length); / / get the size of each read readSize = currentSize + readSize b.FileName = = fileName) .SingleOrDefault () CurrBar.CurrBar = currentSize; currBar.Status = currentSize > = totalSize? 2: 1; _ cache.Set (cacheKey03, bars); System.Threading.Thread.Sleep (1000 * 1) }, file);} / / the task is waiting. You must wait here, or you will lose the uploaded file stream Task.WaitAll (tasks). Data.Msg = "upload complete"; data.Status = 2;} catch (Exception ex) {data.Msg = ex.Message;} return Json (data);}
As for the Action that acquires the upload progress, it only reads the cache data:
[HttpPost] public JsonResult ProgresBar03 () {var bars = new List (); try {bars = _ cache.Get (cacheKey03);} catch (Exception ex) {} return Json (bars);}
Here is the entity class of the upload progress:
Public class MoData {/ 0: failed 1: uploading 2: success / public int Status {get; set;} public string Msg {get; set;}} public class MoBar: MoData {/ File name / public string FileName {get; set } / current upload size / public long CurrBar {get; set;} / Total size / public long TotalBar {get; set } /% progress / public string PercentBar {get {return $"{(this.CurrBar * 100 / this.TotalBar)}%";}
At this point, the way the task task handles uploading files is completed. Let's take a look at the figure to see the effect:
You can compare the effect of not using Task and using it through the effect diagrams of examples 3 and 4, so you deserve to have the effect. Friends who have read this article patiently will not let you down. If you can click "like" or scan the code to support the author, thank you. Finally, the content is accompanied by specific test case code: several examples of .NetCore uploading multiple files.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.