Some time ago the project on-line, too busy, recent research study can finally start the ASP.NET Core.
Going to write a series, but I have not figured out the directory, today a first-come, finishing behind it.
ASP.NET Core 2.0 to the present, has been very mature. The next project for the use of it.
1. Using the model binding upload files (the official example)
The official address of machine translation: https: //docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
Here Tucao about - - It TM machine translation .. not as their own to see the text of the E ..
First we need to create a form form as follows:
<form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave"> <div> <div> <p>Form表单多个上传文件:</p> <input type="file" name="files" multiple /> <input type="submit" value="上传" /> </div> </div> </form>
Which, ASP-the Controller and asp-action, (this is TagHelper play, after speaking) is the controller and the way we want to access.
Give our input tag plus multiple properties, to support multiple file uploads.
Create a controller, we write the upload method is 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, free. "" Long fileSize = formFile.Length; // get file size, in bytes String newfilename = System.Guid.NewGuid () the ToString () +. " . " + FileExt; // randomly generates a new file name var filePath = webRootPath + " / Upload / " + newfilename; the using ( var Stream = new new the FileStream (filePath, FileMode.Create)) { the await formFile.CopyToAsync (Stream); } } } return Ok ( new new { count = files.Count, size }); }
Here we use a new interface Asp.NET Core IFormFile, IFormFile is defined 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 get the address of the root directory of the project.
Constructor injection code is as follows:
private readonly IHostingEnvironment _hostingEnvironment; public UpLoadFileController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; }
In this way, we completed the preparation of the controller, and then run to the front, upload files .. effect is as follows:
By IFormFile of CopyToAsync method, we can put this file and save it to flow down the local copy can be.
2. Use Ajax upload files
Above we are using the upload form, but the course of the project, most cases will use Ajax to upload, so we can say something about how to use Ajax to upload.
First write HTML code is as follows:
<div> <form id="uploadForm"> AJAX上传多文件: <input type="file" name="file" multiple /> <input type="button" value="上传" onclick="doUpload()" /> </form> </div>
Write JS code is as follows (here we use FormData objects 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); } }); }
Background code without making any changes. We will find direct in List <IFormFile> files are unable to get to the file.
By commissioning, we can see that the file is uploaded successfully, but on the Request.Form.Files them.
Background So modified 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, free Long fileSize = formFile.Length; // get file size, in bytes string newFileName = System.Guid.NewGuid () ToString ( ) + + fileExt. "."; // randomly generates a new file name var filePath = webRootPath + "/ Upload /" + newfilename; the using ( var Stream = new new the FileStream (filePath, FileMode.Create)) { the await formFile.CopyToAsync (Stream); } } } return Ok ( new new {COUNT = files.Count, size}); }
To direct from Request.Form.Files get the collection of files. ~
3. Use webUploader upload files
.. .. uh long ago had a package of JS webUploader follows:
.. We also try to use encapsulated .HTML and JS JS code below, not need to modify the code behind, or directly from Request.Form.Files acquired to:
<div id="upfliediv"></div>
$ ( Function () { // instantiate file upload $ ( "#upfliediv" ) .powerWebUpload ({ Auto: to true , fileNumLimit:. 1 }); $ ( "#upfliediv" ) .CleanUpload (); })
Upload effect is shown:
4. Download the file.
Upload a file, we certainly need to download.
直接通过URL+地址下载是一种极其不安全的方式.这里我们采用返回流的形式来下载.
后台代码如下:
/// <summary> /// 文件流的方式输出 /// </summary> /// <returns></returns> public IActionResult DownLoad(string file) { var addrUrl = file; var stream = System.IO.File.OpenRead(addrUrl); string fileExt = GetFileExt(file); //获取文件的ContentType var provider = new FileExtensionContentTypeProvider(); var memi = provider.Mappings[fileExt]; return File(stream, memi, Path.GetFileName(addrUrl)); }
这里值得注意的是,以前我们想获取ContentType直接使用MimeMapping.GetMimeMapping(file);就好了.
但是这个类是在System.Web下的,core已经抛弃了现有的System.Web.
所以在ASP.NET Core中我们需要通过新的类FileExtensionContentTypeProvider来获取文件的ContentType
编写HTML+JS代码如下(PS:因为是demo,所以写的比较简陋):
<div> <input type="text" id="filename" /><button onclick="downLoad()">下载</button> </div>
function downLoad() { var filename = $("#filename").val(); window.location.href = "@Url.Action("DownLoad")?file=" + filename; }
The effect is as:
This herein, this is over, interested, please followers or recommendation. ~ Thank you. Blog also added Article Category ASP.NET Core, and later on ASP.NET Core articles will be categorized on the inside.