相关内容    简体    繁体

asp.net core Webapi 3.1 上传文件的多种方法(附大文件上传) 以及swagger ui 上传文件


直接上干货了

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 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             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, 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             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:测试的不同效果截图

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



猜您在找 asp.net core webapi文件上传 如何在ASP.NET Core中上传超大文件 asp.net core 上传大文件设置 asp.net core流式上传大文件 如何在ASP.NET Core中上传超大文件 asp.net上传超大文件 ASP.NET Core MVC如何上传文件及处理大文件上传 Asp.Net Core WebApi 和Asp.Net WebApi上传文件 WebAPI上传大文件 Asp.Net WebApi 上传文件方法(原生js上传和JQ ajax上传)
 
粤ICP备18138465号  © 2018-2024 CODEPRJ.COM

聚圣源艺龙旅游指南花与蛇1约炮是什么意思拆除公司起名大全余姓字取名起名大全校长述职述廉报告海天盛宴电影武汉纳杰人才网起重吊带十大名牌梦到死去的奶奶朗读者葛小光神医喜来乐下载给属猪的女孩起个小名菩萨蛮温庭筠济南联通gmail注册覃起名字宝宝起名秦我的贴身校花全文阅读edius下载姜倾心霍栩全文免费阅读无弹窗湖北影视在线地火用毅字起名国务院建议试行企业休眠制度朵拉和捣蛋鬼拼写房东管理群起名连城耽美拥兵天下淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻让美丽中国“从细节出发”清明节放假3天调休1天男孩疑遭霸凌 家长讨说法被踢出群国产伟哥去年销售近13亿网友建议重庆地铁不准乘客携带菜筐雅江山火三名扑火人员牺牲系谣言代拍被何赛飞拿着魔杖追着打月嫂回应掌掴婴儿是在赶虫子山西高速一大巴发生事故 已致13死高中生被打伤下体休学 邯郸通报李梦为奥运任务婉拒WNBA邀请19岁小伙救下5人后溺亡 多方发声王树国3次鞠躬告别西交大师生单亲妈妈陷入热恋 14岁儿子报警315晚会后胖东来又人满为患了倪萍分享减重40斤方法王楚钦登顶三项第一今日春分两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?周杰伦一审败诉网易房客欠租失踪 房东直发愁男子持台球杆殴打2名女店员被抓男子被猫抓伤后确诊“猫抓病”“重生之我在北大当嫡校长”槽头肉企业被曝光前生意红火男孩8年未见母亲被告知被遗忘恒大被罚41.75亿到底怎么缴网友洛杉矶偶遇贾玲杨倩无缘巴黎奥运张立群任西安交通大学校长黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发妈妈回应孩子在校撞护栏坠楼考生莫言也上北大硕士复试名单了韩国首次吊销离岗医生执照奥巴马现身唐宁街 黑色着装引猜测沈阳一轿车冲入人行道致3死2伤阿根廷将发行1万与2万面值的纸币外国人感慨凌晨的中国很安全男子被流浪猫绊倒 投喂者赔24万手机成瘾是影响睡眠质量重要因素春分“立蛋”成功率更高?胖东来员工每周单休无小长假“开封王婆”爆火:促成四五十对专家建议不必谈骨泥色变浙江一高校内汽车冲撞行人 多人受伤许家印被限制高消费

聚圣源 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化