1. 程式人生 > 實用技巧 >asp.net core Webapi 3.1 上傳檔案的多種方法(附大檔案上傳) 以及swagger ui 上傳檔案

asp.net core Webapi 3.1 上傳檔案的多種方法(附大檔案上傳) 以及swagger ui 上傳檔案

asp.net core Webapi是有多種上傳檔案的方法的 另外swagger ui也可以選擇檔案來上傳檔案

下面直接上code

1:WebApi後端程式碼

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Threading.Tasks;
  5 
  6 namespace ZRFCoreTestMongoDB.Controllers
  7 {
  8     using Microsoft.AspNetCore.Authorization;
9 using Microsoft.AspNetCore.Mvc.Filters; 10 using Microsoft.AspNetCore.Mvc; 11 using ZRFCoreTestMongoDB.Model; 12 using ZRFCoreTestMongoDB.Commoms; 13 14 15 using Microsoft.IdentityModel.Tokens; 16 using System.Text; 17 using System.Security.Claims; 18 using
System.IdentityModel.Tokens.Jwt; 19 using Microsoft.AspNetCore.Http; 20 using System.IO; 21 using Microsoft.AspNetCore.Hosting; 22 23 24 /// <summary> 25 /// 26 /// </summary> 27 [ApiController] 28 [Route("api/[Controller]")] 29 public class MyJwtTestController : ControllerBase
30 { 31 private readonly JwtConfigModel _jsonmodel; 32 private IWebHostEnvironment _evn; 33 public MyJwtTestController(IWebHostEnvironment evn) 34 { 35 this._evn = evn; 36 _jsonmodel = AppJsonHelper.InitJsonModel(); 37 } 38 39 #region CoreApi檔案上傳 40 41 [HttpPost, Route("UpFile")] 42 public async Task<ApiResult> UpFile([FromForm]IFormCollection formcollection) 43 { 44 ApiResult result = new ApiResult(); 45 try 46 { 47 var files = formcollection.Files;//formcollection.Count > 0 這樣的判斷為錯誤的 48 if (files != null && files.Any()) 49 { 50 var file = files[0]; 51 string contentType = file.ContentType; 52 string fileOrginname = file.FileName;//新建文字文件.txt 原始的檔名稱 53 string fileExtention = Path.GetExtension(fileOrginname); 54 string cdipath = Directory.GetCurrentDirectory(); 55 56 string fileupName = Guid.NewGuid().ToString("d") + fileExtention; 57 string upfilePath = Path.Combine(cdipath + "/myupfiles/", fileupName); 58 if (!System.IO.File.Exists(upfilePath)) 59 { 60 using var Stream = System.IO.File.Create(upfilePath); 61 } 62 63 #region MyRegion 64 //using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) 65 //{ 66 // using (Stream stream = file.OpenReadStream()) //理論上這個方法高效些 67 // { 68 // await stream.CopyToAsync(fileStream);//ok 69 // result.message = "上傳成功!"; result.code = statuCode.success; 70 // } 71 //} 72 73 //using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) 74 //{ 75 // await file.CopyToAsync(fileStream);//ok 76 // result.message = "上傳成功!"; result.code = statuCode.success; 77 //} 78 79 #endregion 80 81 double count = await UpLoadFileStreamHelper.UploadWriteFileAsync(file.OpenReadStream(), upfilePath); 82 result.message = "上傳成功!"; result.code = statuCode.success; result.data = $"上傳的檔案大小為:{count}MB"; 83 } 84 } 85 catch (Exception ex) 86 { 87 result.message = "上傳異常,原因:" + ex.Message; 88 } 89 return result; 90 91 } 92 93 /// <summary> 94 /// 檔案上傳 [FromForm]需要打上這個特性 95 /// </summary> 96 /// <param name="model">上傳的欄位固定為: file</param> 97 /// <returns></returns> 98 99 [HttpPost, Route("UpFile02")] 100 public async Task<ApiResult> UpFileBymodel([FromForm]UpFileModel model)// 這裡一定要加[FromForm]的特性,模型裡面可以不用加 101 { 102 ApiResult result = new ApiResult(); 103 try 104 { 105 bool falg = await UpLoadFileStreamHelper.UploadWriteFileByModelAsync(model); 106 result.code = falg ? statuCode.success : statuCode.fail; 107 result.message = falg ? "上傳成功" : "上傳失敗"; 108 } 109 catch (Exception ex) 110 { 111 result.message = "上傳異常,原因:" + ex.Message; 112 } 113 return result; 114 } 115 116 [HttpPost, Route("UpFile03")] 117 public async Task<ApiResult> UpFile03(IFormFile file)// 這裡一定要加[FromForm]的特性,模型裡面可以不用加 118 { 119 ApiResult result = new ApiResult(); 120 try 121 { 122 bool flag = await UpLoadFileStreamHelper.UploadWriteFileAsync(file); 123 result.code = flag ? statuCode.success : statuCode.fail; 124 result.message = flag ? "上傳成功" : "上傳失敗"; 125 } 126 catch (Exception ex) 127 { 128 result.message = "上傳異常,原因:" + ex.Message; 129 } 130 return result; 131 } 132 #endregion 133 } 134 }
View Code

2: 自定義的json配置檔案

1 {
2 
3   "upfileInfo": {
4     //上傳存放檔案的根目錄
5     "uploadFilePath": "/Myupfiles/"
6   }
7 }
View Code

3:讀取自定義的json檔案

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 
 6 namespace ZRFCoreTestMongoDB.Commoms
 7 {
 8     using ZRFCoreTestMongoDB.Model;
 9     using Microsoft.Extensions.Configuration;
10     public class AppJsonHelper
11     {
12         /// <summary>
13         /// 固定的寫法
14         /// </summary>
15         /// <returns></returns>
16         public static JwtConfigModel InitJsonModel()
17         {
18             string key = "key_myjsonfilekey";
19             JwtConfigModel cachemodel = SystemCacheHelper.GetByCache<JwtConfigModel>(key);
20             if (cachemodel == null)
21             {
22                 ConfigurationBuilder builder = new ConfigurationBuilder();
23                 var broot = builder.AddJsonFile("./configs/zrfjwt.json").Build();
24                 cachemodel = broot.GetSection("jwtconfig").Get<JwtConfigModel>();
25                 SystemCacheHelper.SetCacheByFile<JwtConfigModel>(key, cachemodel);
26             }
27             return cachemodel;
28         }
29 
30         /// <summary>
31         /// 獲取到配置檔案內容的實體
32         /// </summary>
33         /// <typeparam name="T"></typeparam>
34         /// <param name="jsonName">jason 配置檔案中內容節點</param>
35         /// <param name="jsonFilePath">./configs/zrfjwt.json  json檔案的路徑需要始終賦值一下</param>
36         /// <returns></returns>
37         public static T GetJsonModelByFilePath<T>(string jsonName,string jsonFilePath)
38         {
39             if (!string.IsNullOrEmpty(jsonName))
40             {
41                 ConfigurationBuilder builder = new ConfigurationBuilder();
42                 var broot = builder.AddJsonFile(jsonFilePath).Build();
43                 T model = broot.GetSection(jsonName).Get<T>();
44                 return model;
45             }
46             return default;
47         }
48     }
49 }
View Code

4:上傳檔案的測試幫助類

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Threading.Tasks;
  5 
  6 namespace ZRFCoreTestMongoDB.Commoms
  7 {
  8     using Microsoft.AspNetCore.Http;
  9     using Microsoft.AspNetCore.Mvc;
 10     using System.IO;
 11     using ZRFCoreTestMongoDB.Model;
 12     public class UpLoadFileStreamHelper
 13     {
 14         const int FILE_WRITE_SIZE = 1024 * 1024 * 2;
 15         /// <summary>
 16         /// 同步上傳的方法WriteFile(Stream stream, string path)
 17         /// </summary>
 18         /// <param name="stream">檔案流</param>
 19         /// <param name="path">物理路徑</param>
 20         /// <returns></returns>
 21         public static double UploadWriteFile(Stream stream, string path)
 22         {
 23             try
 24             {
 25                 double writeCount = 0;
 26                 using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, FILE_WRITE_SIZE))
 27                 {
 28                     Byte[] by = new byte[FILE_WRITE_SIZE];
 29                     int readCount = 0;
 30                     while ((readCount = stream.Read(by, 0, by.Length)) > 0)
 31                     {
 32                         fileStream.Write(by, 0, readCount);
 33                         writeCount += readCount;
 34                     }
 35                     return Math.Round((writeCount * 1.0 / (1024 * 1024)), 2);
 36                 }
 37             }
 38             catch (Exception ex)
 39             {
 40 
 41                 throw new Exception("發生異常:" + ex.Message);
 42             }
 43         }
 44         /// <summary>
 45         /// WriteFileAsync(Stream stream, string path)
 46         /// </summary>
 47         /// <param name="stream">檔案流</param>
 48         /// <param name="path">物理路徑</param>
 49         /// <returns></returns>
 50         public static async Task<double> UploadWriteFileAsync(Stream stream, string path)
 51         {
 52             try
 53             {
 54                 double writeCount = 0;
 55                 using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, FILE_WRITE_SIZE))
 56                 {
 57                     Byte[] by = new byte[FILE_WRITE_SIZE];
 58 
 59                     int readCount = 0;
 60                     while ((readCount = await stream.ReadAsync(by, 0, by.Length)) > 0)
 61                     {
 62                         await fileStream.WriteAsync(by, 0, readCount);
 63                         writeCount += readCount;
 64                     }
 65                 }
 66                 return Math.Round((writeCount * 1.0 / (1024 * 1024)), 2);
 67             }
 68             catch (Exception ex)
 69             {
 70 
 71                 throw new Exception("發生異常:" + ex.Message);
 72             }
 73         }
 74 
 75         /// <summary>
 76         /// 上傳檔案,需要自定義上傳的路徑
 77         /// </summary>
 78         /// <param name="file">檔案介面物件</param>
 79         /// <param name="path">需要自定義上傳的路徑</param>
 80         /// <returns></returns>
 81         public static async Task<bool> UploadWriteFileAsync(IFormFile file, string path)
 82         {
 83             try
 84             {
 85                 using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, FILE_WRITE_SIZE))
 86                 {
 87                     await file.CopyToAsync(fileStream);
 88                     return true;
 89                 }
 90             }
 91             catch (Exception ex)
 92             {
 93                 throw new Exception("發生異常:" + ex.Message);
 94             }
 95         }
 96 
 97         /// <summary>
 98         /// 上傳檔案,配置資訊從自定義的json檔案中拿取
 99         /// </summary>
100         /// <param name="file"></param>
101         /// <returns></returns>
102         public static async Task<bool> UploadWriteFileAsync(IFormFile file)
103         {
104             try
105             {
106                 if (file != null && file.Length > 0)
107                 {
108                     string contentType = file.ContentType;
109                     string fileOrginname = file.FileName;//新建文字文件.txt  原始的檔名稱
110                     string fileExtention = Path.GetExtension(fileOrginname);//判斷檔案的格式是否正確
111                     string cdipath = Directory.GetCurrentDirectory();
112 
113                     // 可以進一步寫入到系統自帶的配置檔案中
114                     UpFIleModelByJson model = AppJsonHelper.GetJsonModelByFilePath<UpFIleModelByJson>("upfileInfo", "./configs/upfile.json");
115 
116                     string fileupName = Guid.NewGuid().ToString("d") + fileExtention;
117                     string upfilePath = Path.Combine(cdipath + model.uploadFilePath , fileupName);//"/myupfiles/" 可以寫入到配置檔案中
118                     if (!System.IO.File.Exists(upfilePath))
119                     {
120                         using var Stream = System.IO.File.Create(upfilePath);
121                     }
122                     using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, FILE_WRITE_SIZE))
123                     {
124                         await file.CopyToAsync(fileStream);
125                         return true;
126                     }
127                 }
128                 return false;
129             }
130             catch (Exception ex)
131             {
132                 throw new Exception("發生異常:" + ex.Message);
133             }
134         }
135 
136 
137         public static async Task<bool> UploadWriteFileByModelAsync(UpFileModel model)
138         {
139             try
140             {
141                 var files = model.file.Files;// formcollection.Files;//formcollection.Count > 0 這樣的判斷為錯誤的
142                 if (files != null && files.Any())
143                 {
144                     var file = files[0];
145                     string contentType = file.ContentType;
146                     string fileOrginname = file.FileName;//新建文字文件.txt  原始的檔名稱
147                     string fileExtention = Path.GetExtension(fileOrginname);//判斷檔案的格式是否正確
148                     string cdipath = Directory.GetCurrentDirectory();
149                     string fileupName = Guid.NewGuid().ToString("d") + fileExtention;
150                     string upfilePath = Path.Combine(cdipath + "/myupfiles/", fileupName);//可以寫入到配置檔案中
151                     if (!System.IO.File.Exists(upfilePath))
152                     {
153                         using var Stream = System.IO.File.Create(upfilePath);
154                     }
155                     using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
156                     {
157                         using (Stream stream = file.OpenReadStream()) //理論上這個方法高效些
158                         {
159                             await stream.CopyToAsync(fileStream);
160                             return true;
161                         }
162                     }
163                 }
164             }
165             catch (Exception ex)
166             {
167                 throw new Exception("發生異常:" + ex.Message);
168             }
169             return false;
170         }
171 
172         /*
173          webapi 端的程式碼
174 
175         [HttpPost, Route("UpFile02")]
176         public async Task<ApiResult> UpFileBymodel([FromForm]UpFileModel model)// 這裡一定要加[FromForm]的特性,模型裡面可以不用加
177         {
178             ApiResult result = new ApiResult();
179             try
180             {
181                 bool falg = await UpLoadFileStreamHelper.UploadFileByModel(model);
182                 result.code = falg ? statuCode.success : statuCode.fail;
183                 result.message = falg ? "上傳成功" : "上傳失敗";
184             }
185             catch (Exception ex)
186             {
187                 result.message = "上傳異常,原因:" + ex.Message;
188             }
189             return result;
190         }
191          */
192     }
193 
194     public class UpFileModel
195     {
196         public IFormCollection file { get; set; }
197     }
198 }
View Code

5:全域性大檔案上傳的使用:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Hosting;
 6 using Microsoft.Extensions.Configuration;
 7 using Microsoft.Extensions.Hosting;
 8 using Microsoft.Extensions.Logging;
 9 
10 namespace CoreTestMongoDB
11 {
12     public class Program
13     {
14         public static void Main(string[] args)
15         {
16             CreateHostBuilder(args).Build().Run();
17         }
18 
19         public static IHostBuilder CreateHostBuilder(string[] args) =>
20             Host.CreateDefaultBuilder(args)
21                 .ConfigureWebHostDefaults(webBuilder =>
22                 {
23                     webBuilder.UseStartup<Startup>();
24                     webBuilder.ConfigureKestrel(c => c.Limits.MaxRequestBodySize = 1024 * 1024 * 300); // 全域性的大小300M
25                 }).UseServiceProviderFactory(new Autofac.Extensions.DependencyInjection.AutofacServiceProviderFactory());
26     }
27 }
View Code

6:最後上傳成功的效果截圖

7:測試的不同效果截圖