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

时间:2023-03-09 03:52:20
AspNetCore 文件上传(模型绑定、Ajax) 两种方式 get到了吗?

就目前来说,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" name="files" 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 > ) {
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 }); }

这里我们采用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中获取文件集合.