Example of asp.net core multipart Upload File, asp. netcore

Source: Internet
Author: User

Example of asp.net core multipart Upload File, asp. netcore

After writing the asp.net multi-File Upload, I feel that this upload still has many defects... (10 thousand words are omitted, not nonsense ). I chose the open-source asp.net core instead of the traditional asp.net core. The reason is very simple ,. net core is. net. net and. the future of net developers. net development is getting better and better (everyone's salary is getting higher and higher )).

1. Front-end implementation:

12.16.html:

<Html> 

2). javascript:

Var UploadPath = ""; // start upload function UploadStart () {var file = $ ("# path") [0]. files [0]; AjaxFile (file, 0);} function AjaxFile (file, I) {var name = file. name, // file name size = file. size, // total size shardSize = 2*1024*1024, shardSize = 2*1024*1024, // shardCount = Math. ceil (size/shardSize); // total number of slices if (I> = shardCount) {return;} // calculates the start and end positions of each slice var start = I * shardSize, end = Math. min (size, st Art + shardSize); // construct a form. FormData is the newly added var form = new FormData (); form. append ("data", file. slice (start, end); // The slice method is used to cut out a part of the form. append ("lastModified", file. lastModified); form. append ("fileName", name); form. append ("total", shardCount); // The total number of slices form. append ("index", I + 1); // The number of UploadPath = file. lastModified // submit the file through Ajax $. ajax ({url: "/Upload/UploadFile", type: "POST", data: form, Ync: true, // asynchronous processData: false, // It is very important to tell jquery not to process form contentType: false, // It is very important, if it is set to false, the correct Content-Type success: function (result) {if (result! = Null) {I = result. number ++; var num = Math. ceil (I * 100/shardCount); $ ("# output "). text (num + '%'); AjaxFile (file, I); if (result. mergeOk) {var filepath = $ ("# path"); filepath. after (filepath. clone (). val (""); filepath. remove (); // clear input file $ ('# upfile '). val ('select A file'); alert ("success !!! ");}}}});}

The main idea here is to use the slice Method of the html5 File api to block the File, and then use a new FormData () object to store the File data, and then call the AjaxFile method recursively until the upload is complete.

2. Background C #:

Using System; using System. collections. generic; using System. linq; using System. threading. tasks; using Microsoft. aspNetCore. mvc; using System. IO; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace DotNet. upload. controllers {public class UploadController: Controller {// GET:/<controller>/public IActionResult Index () {return View ();} [HttpPost] public async Task <ActionResult> UploadFile () {var data = Request. form. files ["data"]; string lastModified = Request. form ["lastModified"]. toString (); var total = Request. form ["total"]; var fileName = Request. form ["fileName"]; var index = Request. fo Rm ["index"]; string temporary = Path. Combine (@ "E: \ Browser", lastModified); // temporarily Save the partition directory try {if (! Directory. Exists (temporary) Directory. CreateDirectory (temporary); string filePath = Path. Combine (temporary, index. ToString (); if (! Convert. isDBNull (data) {await Task. run () => {FileStream fs = new FileStream (filePath, FileMode. create); data. copyTo (fs) ;}) ;}bool mergeOk = false; if (total = index) {mergeOk = await FileMerge (lastModified, fileName);} Dictionary <string, object> result = new Dictionary <string, object> (); result. add ("number", index); result. add ("mergeOk", mergeOk); return Json (result);} catch (Exception ex) {Directory. delete (temporary); // Delete the folder throw ex ;}} public async Task <bool> FileMerge (string lastModified, string fileName) {bool OK = false; try {var temporary = Path. combine (@ "E: \ Browser", lastModified); // Temporary Folder fileName = Request. form ["fileName"]; // file name string fileExt = Path. getExtension (fileName); // get the file suffix var files = Directory. getFiles (temporary); // obtain all the following files var finalPath = Path. combine (@ "E: \ Browser", DateTime. now. toString ("yyMMddHHmmss") + fileExt); // The final file name (the file name stored in the demo is the uploaded file name. This is definitely not the case in actual operations) var fs = new FileStream (finalPath, FileMode. create); foreach (var part in files. orderBy (x => x. length ). thenBy (x => x) // sort the order to ensure that the Write from 0-N {var bytes = System. IO. file. readAllBytes (part); await fs. writeAsync (bytes, 0, bytes. length); bytes = null; System. IO. file. delete (part); // Delete part} fs. close (); Directory. delete (temporary); // Delete folder OK = true;} catch (Exception ex) {throw ex;} return OK ;}}}

The idea here is to save each part of the file to a temporary folder, and then merge these temporary files through FileStream (the merge must be in order ). The backend methods are all asynchronous (async await is really useful). Although I don't know whether the efficiency is improved, I think it is so cool.

Source code download: DotNet_jb51.rar

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.