Asp.Net Core 文件上传处理

时间:2022-06-23 10:08:02

本文主要介绍后台接收处理

1.在使用控制器接收

   : [HttpPost]
: public IActionResult UploadFiles(IList<IFormFile> files)
: {
: long size = ;
: foreach(var file in files)
: {
: var filename = ContentDispositionHeaderValue
: .Parse(file.ContentDisposition)
: .FileName
: .Trim('"');
: filename = hostingEnv.WebRootPath + $@"\{fileName}";
: size += file.Length;
: using (FileStream fs = System.IO.File.Create(filename))
: {
: file.CopyTo(fs);
: fs.Flush();
: }
: }

2.使用HttpRequest接收

方式1:

   : [HttpPost]
: public IActionResult UploadFilesAjax()
: {
: long size = ;
: var files = Request.Form.Files;
: foreach (var file in files)
: {
: var filename = ContentDispositionHeaderValue
: .Parse(file.ContentDisposition)
: .FileName
: .Trim('"');
: filename = hostingEnv.WebRootPath + $@"\{filename}";
: size += file.Length;
: using (FileStream fs = System.IO.File.Create(filename))
: {
: file.CopyTo(fs);
: fs.Flush();
: }
: }
: string message = $"{files.Count} file(s) /
: {size} bytes uploaded successfully!";
: return Json(message);
: }

方式2:

    //接收文件
var files = req.Form.Files;
if (files.Count <= )
throw new Exception("获取上传文件失败");
IFormFile _file = files[];
string backInfo = req.Form["backinfo"];
if (string.IsNullOrEmpty(backInfo))
throw new Exception("获取文件信息失败");
UploadMsg upMsg = backInfo.JsonDeserializer<UploadMsg>();
this.file = new UploadInfo(upMsg);
//获取文件数据
Stream stream = _file.OpenReadStream();
try
{
byte[] dataOne = new byte[stream.Length];
stream.Read(dataOne, , dataOne.Length);
AppendFile(dataOne);
}
finally
{
stream.Close();
}

支持.Net Core的上传控件:https://github.com/tianma3798/Uploader

更多:

Asp.Net Core获取当前上线文对象

Asp.Net Core 视图整理(一)

Asp.Net Core异常处理整理