AspNetCore 文件上传(模型绑定、Ajax) 两种方式 get到了吗?

发布时间:2021-07-31 23:48 来源:https://blog.51cto.com/u_15316 阅读:58 作者:mb6100f4ef45bc6 栏目: 云计算

就目前来说,ASP.NET Core2.1了,已经相当成熟了,希望下个项目争取使用吧!!

上传文件的三种方式("我会的,说不定还有其他方式")

模型绑定

Ajax

WebUploader

一。模型绑定

  官方机器翻译的地址:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads,吐槽一下,这翻译的啥玩腻啊。。。

<form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave"> <div> <div> <p>Form表单多个上传文件:</p> <input type="file" multiple /> <input type="submit" value="上传" /> </div> </div> </form>

  其中,asp-controller和asp-action,(这个是TagHelper的玩法)是我们要访问的控制器和方法,不懂taghelper的可以看一下我关于aspnetcore的taghelper的相关文章zara说taghelper

  给我们的input标签加上 multiple 属性,来支持多文件上传.

创建一个控制器,我们编写上传方法如下:

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); //文件扩展名,不含“.” long fileSize = formFile.Length; //获得文件大小,以字节为单位 string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名 var filePath = webRootPath +"/upload/" + newFileName; using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } } } return Ok(new { count = files.Count, size }); }

View Code

这里我们采用Asp.NET Core的新接口IFormFile,  IFormFile的具体定义如下:

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); }

  上面的代码使用了IHostingEnvironment来获取项目的根目录地址.

构造函数注入的代码如下:

private readonly IHostingEnvironment _hostingEnvironment; public UpLoadFileController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; }

  二。ajax上传

前台代码:

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); } }); }

  

  后台代码和模型绑定有点区别,不要写参数的了,获取直接reques里面的了

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); //文件扩展名,不含“.” long fileSize = formFile.Length; //获得文件大小,以字节为单位 string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名 var filePath = webRootPath +"/upload/" + newFileName; using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } } } return Ok(new { count = files.Count, size }); }

  改为直接从Request.Form.Files中获取文件集合.

 

免责声明:本站发布的内容(图片、视频和文字)以原创、来自互联网转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:ts@56dr.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。