本篇主要介紹下文件的上傳與下載。分享給大家,具體如下:
文件上傳下載也是系統(tǒng)中常用的功能,不啰嗦,直接上代碼看下具體的實(shí)現(xiàn)。
文件上傳
.net core通過(guò) IFormFile 接收文件對(duì)象,再通過(guò)流的方式保存至指定的地方。
[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會(huì)默認(rèn)限制一定的上傳文件大小,可通過(guò) [DisableRequestSizeLimit] 禁用http限制大小,也可通過(guò) [RequestSizeLimit(1024)] 來(lái)指定限制http上傳的大小。
文件下載
相對(duì)于上傳,下載就比較簡(jiǎn)單了,找到指定的文件,轉(zhuǎn)換成流,通過(guò).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(); } }
總結(jié)
文件的上傳下載的基本操作簡(jiǎn)單介紹了下,大家可以嘗試下。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com