.net core下對於附件上傳下載的實現
阿新 • • 發佈:2019-02-13
在上一篇[.net core下對於Excel的一些操作及使用]主要介紹了 .net core下excel的相關操作,本篇主要介紹下檔案的上傳與下載。
檔案上傳下載也是系統中常用的功能,不囉嗦,直接上程式碼看下具體的實現。
檔案上傳
.net core通過IFormFile
接收檔案物件,再通過流的方式儲存至指定的地方。
[HttpPost("upload")]
//[DisableRequestSizeLimit] //禁用http限制大小
[RequestSizeLimit(100*1024*1024)] //限制http大小
public async Task<IActionResult> Post (List<IFormFile> files)
{
try
{
if (files == null || !files.Any())
return AssertNotFound(new ResponseFileResult { Result = false, Code = ResponseCode.InvalidParameters, ErrorMessage = "附件不能為空" });
string filePath = Path.Combine(Directory.GetCurrentDirectory(), BASEFILE, $@"Template" );
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
var result = new ResponseFileResult();
var fileList = new List<FileResultModel>();
foreach (var file in files)
{
var fileModel = new FileResultModel();
var fileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var newName = Guid.NewGuid().ToString() + Path.GetExtension(fileName);
var filefullPath = Path.Combine(filePath, $@"{newName}");
using (FileStream fs = new FileStream(filefullPath, FileMode.Create))//System.IO.File.Create(filefullPath)
{
file.CopyTo(fs);
fs.Flush();
}
fileList.Add(new FileResultModel { Name = fileName, Size = file.Length, Url = $@"/file/download?fileName={newName}" });
}
result.FileResultList = fileList;
return AssertNotFound(result);
}
catch(Exception ex)
{
return AssertNotFound(new ResponseFileResult { Result = false, Code = ResponseCode.UnknownException, ErrorMessage = ex.Message });
}
}
其中http會預設限制一定的上傳檔案大小,可通過[DisableRequestSizeLimit]
禁用http限制大小,也可通過[RequestSizeLimit(1024)]
來指定限制http上傳的大小。
檔案下載
相對於上傳,下載就比較簡單了,找到指定的檔案,轉換成流,通過.net core自帶的File
方法返回流檔案,完成檔案下載:
[HttpGet("download")]
public async Task<IActionResult> Get(string fileName)
{
try
{
var addrUrl = Path.Combine(Directory.GetCurrentDirectory(), BASEFILE, $@"{fileName}");
FileStream fs = new FileStream(addrUrl, FileMode.Open);
return File(fs, "application/vnd.android.package-archive", fileName);
}
catch(Exception ex)
{
return NotFound();
}
}
總結
檔案的上傳下載的基本操作簡單介紹了下,大家可以嘗試下。