Example of an ASP. NET Core Tile upload file

Source: Internet
Author: User
Tags button type
After writing the ASP. Net file upload, I feel this kind of upload still has a lot of flaws, so ... (Omit 10,000 words, no nonsense). I didn't use the traditional ASP. NET, and I chose the Open source ASP. The reason for this is simple, the new beginning of. NET core, the future of. NET and. NET developers, and the hope that. NET will grow better (everyone's pay is getting higher (ˇ∀ˇ)).

1. Front-End implementation:

1). HTML:

2). javascript:

var uploadpath = "";//Start uploading 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 * 1024x768 * 1024x768, shardsize = 2 * 1024 * 1024,//with 2MB for a shard Shardcount = Math.ceil (size/shardsize);  Total number of pieces if (I >= shardcount) {return;  }//Calculates the start and end position of each piece var start = i * shardsize, end = math.min (size, start + shardsize);  Constructs a form, FormData is the HTML5 new var form = new FormData (); Form.append ("Data", File.slice (Start, end));  The slice method is used to cut out a portion of a file Form.append ("LastModified", file.lastmodified);  Form.append ("FileName", name); Form.append ("Total", shardcount); Total number of pieces form.append ("index", i + 1); Current is the first few slices Uploadpath = file.lastmodified//ajax Commit file $.ajax ({url: "/upload/uploadfile", type: "POST", data:for M, Async:true,//asynchronous Processdata:false,//It is important to tell jquery not to process the form contenttype:false,//It is important to specify false to form the correct conte      Nt-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 ();//Empty input file $ (' #upfile '). val (' Please select file ');        Alert ("Success!!!"); }      }    }  });}

The main idea here is to use the slice method of the HTML5 file API to block files, and then new a formdata () object to store the file data, and then recursively call the Ajaxfile method 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://www.php.    Cn/namespace 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.form["index"]; String temporary = Path.Combine (@ "E:\ browser", lastmodified);//temporarily save the chunked 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 folder throw ex;      }} public Async task<bool> Filemerge (String lastmodified,string fileName) {bool OK = false; try {var temporary = Path.Combine (@ "E:\ browser", lastmodified);//Temp folder filename = request.form["filename"] ;//filename String fileext = path.getextension (filename);//Get file suffix var files = directory.getfiles (temporary);//Get under All files of the polygon var Finalpath = Path.Combine (@ "E:\ Browser ", DateTime.Now.ToString (" Yymmddhhmmss ") + Fileext);//The final file name (the demo saves the file name when it is uploaded, and the actual operation must not) var fs = new Filest        Ream (Finalpath, FileMode.Create); foreach (var part in files. (x = x.length).          ThenBy (x = x))//row order, guaranteed from 0-n Write {var bytes = System.IO.File.ReadAllBytes (part); Await FS. WriteAsync (bytes, 0, bytes.          Length);          bytes = NULL; System.IO.File.Delete (part);//Delete chunked} fs.        Close ();      Directory.delete (temporary);//delete Folder OK = true;      } catch (Exception ex) {throw ex;    } return OK; }  }}

The idea here is to first save each chunk of the file to a temporary folder, and then merge the temporary files with FileStream (the merge must be in order). The back-end methods are all asynchronous (async await is really handy), although I don't know if there's any improvement in efficiency, but it's cool.

SOURCE Download: Dotnet_jb51.rar

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.