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 try104  {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 try121  {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 #endregion133  }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 AppJsonHelper11  {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 WRITE_FILE_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, WRITE_FILE_SIZE)) 27  { 28 Byte[] by = new byte[WRITE_FILE_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, WRITE_FILE_SIZE)) 56  { 57 Byte[] by = new byte[WRITE_FILE_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, WRITE_FILE_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 try105  {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, WRITE_FILE_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 try140  {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  try180  {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 UpFileModel195  {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 CoreTestMongoDB11 {12 public class Program13  {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); // 全局的大小300M25 }).UseServiceProviderFactory(new Autofac.Extensions.DependencyInjection.AutofacServiceProviderFactory());26  }27 }

View Code

6:最后上传成功的效果截图

技术图片

 

 7:测试的不同效果截图

技术图片

 

 技术图片

 

相关文章