ASP. NET Core file upload and download instances (multiple upload methods) and core File Upload
Preface
Some time ago, the project went online, so it was too busy. Recently, I began to study ASP. NET Core.
I plan to write a series, but I haven't thought about the directory yet. Let's take a look at this article today. I will organize it later.
ASP. NET Core 2.0 has developed to the present and is very mature. Try to use it in the next project.
Body
1. Use model binding to upload files (Official example)
Address: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
Let's talk about it here--, this TM machine translation... it's better to read E text by yourself ..
First, create a form as follows:
<Form method = "post" enctype = "multipart/form-data" asp-controller = "UpLoadFile" asp-action = "FileSave"> <div> <p> form multiple upload files: </p> <input type = "file" name = "files" multiple/> <input type = "submit" value = "Upload"/> </div> </form>
Asp-controller and asp-action are the controllers and methods we want to access.
Add the multiple attribute to the input tag to support Multifile upload.
To create a controller, write the upload method as follows:
Public async Task <IActionResult> FileSave (List <IFormFile> files) {var files = Request. form. files; long size = files. sum (f => f. length); string webRootPath = _ hostingEnvironment. webRootPath; string contentRootPath = _ hostingEnvironment. contentRootPath; foreach (var formFile in files) {if (formFile. length> 0) {string fileExt = GetFileExt (formFile. fileName); // file extension, excluding ". "long fileSize = formFile. length; // get the file size, in bytes string newFileName = System. guid. newGuid (). toString () + ". "+ fileExt; // generate a new file name named var filePath = webRootPath +"/upload/"+ newFileName; using (var stream = new FileStream (filePath, FileMode. create) {await formFile. copyToAsync (stream) ;}} return OK (new {count = files. count, size });}
Here we use the new interface IFormFile of Asp. NET Core. The detailed definition of IFormFile is as follows:
public interface IFormFile{ string ContentType { get; } string ContentDisposition { get; } IHeaderDictionary Headers { get; } long Length { get; } string Name { get; } string FileName { get; } Stream OpenReadStream(); void CopyTo(Stream target); Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);}
The above Code uses IHostingEnvironment to obtain the root directory address of the project.
The constructor injection code is as follows:
private readonly IHostingEnvironment _hostingEnvironment; public UpLoadFileController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; }
In this way, we have completed the preparation of the controller, and then to the running front-end, upload the file... the effect is as follows:
Through the CopyToAsync method of IFormFile, we can copy the file stream and save it locally.
2. Use Ajax to upload files
We used form upload, but in most cases, Ajax is used for upload during the project process. So let's talk about how to use Ajax for upload.
First, write the HTML code as follows:
<Div> <form id = "uploadForm"> AJAX: <input type = "file" name = "file" multiple/> <input type = "button" value = "Upload" onclick = "doUpload () "/> </form> </div>
Compile the JS Code as follows (Here we use the FormData object to upload ):
function doUpload() { var formData = new FormData($("#uploadForm")[0]); $.ajax({ url: '@Url.Action("FileSave")', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); }
The background code is not modified. We will find that the file cannot be obtained directly in List <IFormFile> files.
Through debugging, we can find that the file is uploaded successfully, but stored in Request. Form. Files.
Therefore, modify the background Code as follows:
Public async Task <IActionResult> FileSave () {var date = Request; var files = Request. form. files; long size = files. sum (f => f. length); string webRootPath = _ hostingEnvironment. webRootPath; string contentRootPath = _ hostingEnvironment. contentRootPath; foreach (var formFile in files) {if (formFile. length> 0) {string fileExt = GetFileExt (formFile. fileName); // file extension, excluding ". "long fileSize = formFile. length; // get the file size, in bytes string newFileName = System. guid. newGuid (). toString () + ". "+ fileExt; // generate a new file name named var filePath = webRootPath +"/upload/"+ newFileName; using (var stream = new FileStream (filePath, FileMode. create) {await formFile. copyToAsync (stream) ;}} return OK (new {count = files. count, size });}
Instead, retrieve the file set directly from Request. Form. Files .~
3. Use webUploader to upload files
A long time ago, uh... encapsulated a webUploader JS.
.. We also use encapsulated JS to try. HTML and JS Code as follows. The background Code does not need to be modified, or you can directly obtain it from Request. Form. Files:
<div id="upfliediv"></div>
$ (Function () {// upload an instantiated object $ ("# upfliediv "). powerWebUpload ({auto: true, fileNumLimit: 1}); $ ("# upfliediv "). cleanUpload ();})
Upload effect:
4. File Download.
The file has been uploaded. Of course we need to download it.
Directly downloading through URL + address is an extremely insecure method. Here we use the returned stream to download.
The background code is as follows:
/// <Summary> /// file stream output // </summary> /// <returns> </returns> public IActionResult DownLoad (string file) {var addrUrl = file; var stream = System. IO. file. openRead (addrUrl); string fileExt = GetFileExt (file); // obtain the file's ContentType var provider = new FileExtensionContentTypeProvider (); var memi = provider. mappings [fileExt]; return File (stream, memi, Path. getFileName (addrUrl ));}
It is worth noting that we used to use MimeMapping. GetMimeMapping (file) directly for ContentType.
However, this class is under System. Web, and core has abandoned the existing System. Web.
Therefore, in ASP. NET Core, we need to use the new FileExtensionContentTypeProvider class to obtain the ContentType of the file.
Compile the HTML + JS Code as follows (PS: it is simple to write because it is a demo ):
<Div> <input type = "text" id = "filename"/> <button onclick = "downLoad ()"> downLoad </button> </div>
function downLoad() { var filename = $("#filename").val(); window.location.href = "@Url.Action("DownLoad")?file=" + filename;}
Effect:
The above example of uploading and downloading ASP. NET Core files (multiple upload methods) is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for more.