本篇主要介紹下文件的上傳與下載。分享給大家,具體如下:
文件上傳下載也是系統中常用的功能,不啰嗦,直接上代碼看下具體的實現。
文件上傳
.net core通過 IFormFile 接收文件對象,再通過流的方式保存至指定的地方。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
[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 方法返回流文件,完成文件下載:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[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(); } } |
總結
文件的上傳下載的基本操作簡單介紹了下,大家可以嘗試下。以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/99af019284ab