asp.net core Webapi 3.1 上传文件的多种方法(附大文件上传) 以及swagger ui 上传文件
2020-07-30 15:39
1501 查看
直接上干货了
1:WebApi后端代码
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ZRFCoreTestMongoDB.Controllers { using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc; using ZRFCoreTestMongoDB.Model; using ZRFCoreTestMongoDB.Commoms; using Microsoft.IdentityModel.Tokens; using System.Text; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Http; using System.IO; using Microsoft.AspNetCore.Hosting; /// <summary> /// /// </summary> [ApiController] [Route("api/[Controller]")] public class MyJwtTestController : ControllerBase { private readonly JwtConfigModel _jsonmodel; private IWebHostEnvironment _evn; public MyJwtTestController(IWebHostEnvironment evn) { this._evn = evn; _jsonmodel = AppJsonHelper.InitJsonModel(); } #region CoreApi文件上传 [HttpPost, Route("UpFile")] public async Task<ApiResult> UpFile([FromForm]IFormCollection formcollection) { ApiResult result = new ApiResult(); try { var files = formcollection.Files;//formcollection.Count > 0 这样的判断为错误的 if (files != null && files.Any()) { var file = files[0]; string contentType = file.ContentType; string fileOrginname = file.FileName;//新建文本文档.txt 原始的文件名称 string fileExtention = Path.GetExtension(fileOrginname); string cdipath = Directory.GetCurrentDirectory(); string fileupName = Guid.NewGuid().ToString("d") + fileExtention; string upfilePath = Path.Combine(cdipath + "/myupfiles/", fileupName); if (!System.IO.File.Exists(upfilePath)) { using var Stream = System.IO.File.Create(upfilePath); } #region MyRegion //using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) //{ // using (Stream stream = file.OpenReadStream()) //理论上这个方法高效些 // { // await stream.CopyToAsync(fileStream);//ok // result.message = "上传成功!"; result.code = statuCode.success; // } //} //using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) //{ // await file.CopyToAsync(fileStream);//ok // result.message = "上传成功!"; result.code = statuCode.success; //} #endregion double count = await UpLoadFileStreamHelper.UploadWriteFileAsync(file.OpenReadStream(), upfilePath); result.message = "上传成功!"; result.code = statuCode.success; result.data = $"上传的文件大小为:{count}MB"; } } catch (Exception ex) { result.message = "上传异常,原因:" + ex.Message; } return result; } /// <summary> /// 文件上传 [FromForm]需要打上这个特性 /// </summary> /// <param name="model">上传的字段固定为: file</param> /// <returns></returns> [HttpPost, Route("UpFile02")] public async Task<ApiResult> UpFileBymodel([FromForm]UpFileModel model)// 这里一定要加[FromForm]的特性,模型里面可以不用加 { ApiResult result = new ApiResult(); try { bool falg = await UpLoadFileStreamHelper.UploadWriteFileByModelAsync(model); result.code = falg ? statuCode.success : statuCode.fail; result.message = falg ? "上传成功" : "上传失败"; } catch (Exception ex) { result.message = "上传异常,原因:" + ex.Message; } return result; } [HttpPost, Route("UpFile03")] public async Task<ApiResult> UpFile03(IFormFile file)// 这里一定要加[FromForm]的特性,模型里面可以不用加 { ApiResult result = new ApiResult(); try { bool flag = await UpLoadFileStreamHelper.UploadWriteFileAsync(file); result.code = flag ? statuCode.success : statuCode.fail; result.message = flag ? "上传成功" : "上传失败"; } catch (Exception ex) { result.message = "上传异常,原因:" + ex.Message; } return result; } #endregion } }View Code
2: 自定义的json配置文件
{ "upfileInfo": { //上传存放文件的根目录 "uploadFilePath": "/Myupfiles/" } }View Code
3:读取自定义的json文件
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ZRFCoreTestMongoDB.Commoms { using ZRFCoreTestMongoDB.Model; using Microsoft.Extensions.Configuration; public class AppJsonHelper { /// <summary> /// 固定的写法 /// </summary> /// <returns></returns> public static JwtConfigModel InitJsonModel() { string key = "key_myjsonfilekey"; JwtConfigModel cachemodel = SystemCacheHelper.GetByCache<JwtConfigModel>(key); if (cachemodel == null) { ConfigurationBuilder builder = new ConfigurationBuilder(); var broot = builder.AddJsonFile("./configs/zrfjwt.json").Build(); cachemodel = broot.GetSection("jwtconfig").Get<JwtConfigModel>(); SystemCacheHelper.SetCacheByFile<JwtConfigModel>(key, cachemodel); } return cachemodel; } /// <summary> /// 获取到配置文件内容的实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonName">jason 配置文件中内容节点</param> /// <param name="jsonFilePath">./configs/zrfjwt.json json文件的路径需要始终赋值一下</param> /// <returns></returns> public static T GetJsonModelByFilePath<T>(string jsonName,string jsonFilePath) { if (!string.IsNullOrEmpty(jsonName)) { ConfigurationBuilder builder = new ConfigurationBuilder(); var broot = builder.AddJsonFile(jsonFilePath).Build(); T model = broot.GetSection(jsonName).Get<T>(); return model; } return default; } } }View Code
4:上传文件的测试帮助类
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ZRFCoreTestMongoDB.Commoms { using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.IO; using ZRFCoreTestMongoDB.Model; public class UpLoadFileStreamHelper { const int WRITE_FILE_SIZE = 1024 * 1024 * 2; /// <summary> /// 同步上传的方法WriteFile(Stream stream, string path) /// </summary> /// <param name="stream">文件流</param> /// <param name="path">物理路径</param> /// <returns></returns> public static double UploadWriteFile(Stream stream, string path) { try { double writeCount = 0; using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, WRITE_FILE_SIZE)) { Byte[] by = new byte[WRITE_FILE_SIZE]; int readCount = 0; while ((readCount = stream.Read(by, 0, by.Length)) > 0) { fileStream.Write(by, 0, readCount); writeCount += readCount; } return Math.Round((writeCount * 1.0 / (1024 * 1024)), 2); } } catch (Exception ex) { throw new Exception("发生异常:" + ex.Message); } } /// <summary> /// WriteFileAsync(Stream stream, string path) /// </summary> /// <param name="stream">文件流</param> /// <param name="path">物理路径</param> /// <returns></returns> public static async Task<double> UploadWriteFileAsync(Stream stream, string path) { try { double writeCount = 0; using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, WRITE_FILE_SIZE)) { Byte[] by = new byte[WRITE_FILE_SIZE]; int readCount = 0; while ((readCount = await stream.ReadAsync(by, 0, by.Length)) > 0) { await fileStream.WriteAsync(by, 0, readCount); writeCount += readCount; } } return Math.Round((writeCount * 1.0 / (1024 * 1024)), 2); } catch (Exception ex) { throw new Exception("发生异常:" + ex.Message); } } /// <summary> /// 上传文件,需要自定义上传的路径 /// </summary> /// <param name="file">文件接口对象</param> /// <param name="path">需要自定义上传的路径</param> /// <returns></returns> public static async Task<bool> UploadWriteFileAsync(IFormFile file, string path) { try { using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, WRITE_FILE_SIZE)) { await file.CopyToAsync(fileStream); return true; } } catch (Exception ex) { throw new Exception("发生异常:" + ex.Message); } } /// <summary> /// 上传文件,配置信息从自定义的json文件中拿取 /// </summary> /// <param name="file"></param> /// <returns></returns> public static async Task<bool> UploadWriteFileAsync(IFormFile file) { try { if (file != null && file.Length > 0) { string contentType = file.ContentType; string fileOrginname = file.FileName;//新建文本文档.txt 原始的文件名称 string fileExtention = Path.GetExtension(fileOrginname);//判断文件的格式是否正确 string cdipath = Directory.GetCurrentDirectory(); // 可以进一步写入到系统自带的配置文件中 UpFIleModelByJson model = AppJsonHelper.GetJsonModelByFilePath<UpFIleModelByJson>("upfileInfo", "./configs/upfile.json"); string fileupName = Guid.NewGuid().ToString("d") + fileExtention; string upfilePath = Path.Combine(cdipath + model.uploadFilePath , fileupName);//"/myupfiles/" 可以写入到配置文件中 if (!System.IO.File.Exists(upfilePath)) { using var Stream = System.IO.File.Create(upfilePath); } using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, WRITE_FILE_SIZE)) { await file.CopyToAsync(fileStream); return true; } } return false; } catch (Exception ex) { throw new Exception("发生异常:" + ex.Message); } } public static async Task<bool> UploadWriteFileByModelAsync(UpFileModel model) { try { var files = model.file.Files;// formcollection.Files;//formcollection.Count > 0 这样的判断为错误的 if (files != null && files.Any()) { var file = files[0]; string contentType = file.ContentType; string fileOrginname = file.FileName;//新建文本文档.txt 原始的文件名称 string fileExtention = Path.GetExtension(fileOrginname);//判断文件的格式是否正确 string cdipath = Directory.GetCurrentDirectory(); string fileupName = Guid.NewGuid().ToString("d") + fileExtention; string upfilePath = Path.Combine(cdipath + "/myupfiles/", fileupName);//可以写入到配置文件中 if (!System.IO.File.Exists(upfilePath)) { using var Stream = System.IO.File.Create(upfilePath); } using (FileStream fileStream = new FileStream(upfilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (Stream stream = file.OpenReadStream()) //理论上这个方法高效些 { await stream.CopyToAsync(fileStream); return true; } } } } catch (Exception ex) { throw new Exception("发生异常:" + ex.Message); } return false; } /* webapi 端的代码 [HttpPost, Route("UpFile02")] public async Task<ApiResult> UpFileBymodel([FromForm]UpFileModel model)// 这里一定要加[FromForm]的特性,模型里面可以不用加 { ApiResult result = new ApiResult(); try { bool falg = await UpLoadFileStreamHelper.UploadFileByModel(model); result.code = falg ? statuCode.success : statuCode.fail; result.message = falg ? "上传成功" : "上传失败"; } catch (Exception ex) { result.message = "上传异常,原因:" + ex.Message; } return result; } */ } public class UpFileModel { public IFormCollection file { get; set; } } }View Code
5:全局大文件上传的使用:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace CoreTestMongoDB { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.ConfigureKestrel(c => c.Limits.MaxRequestBodySize = 1024 * 1024 * 300); // 全局的大小300M }).UseServiceProviderFactory(new Autofac.Extensions.DependencyInjection.AutofacServiceProviderFactory()); } }View Code
6:最后上传成功的效果截图
7:测试的不同效果截图
相关文章推荐
- 通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传
- 一个简单的QQ隐藏图生成算法 通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传
- asp.net core webapi文件上传
- asp.net core webapi文件上传(转载)
- ASP.Net在web.config中设置上传文件的大小方法 (摘要)
- ASP.Net在web.config中设置上传文件的大小方法
- ASP.NET core Web中使用appsettings.json配置文件的方法
- 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null
- ASP.NET Core WebApi中使用FluentValidation验证数据模型的方法
- ASP.NET Core文件上传与下载(多种上传方式)
- File Upload using jQuery AJAX in ASP.NET Web API or Http handler (AJAX上传文件通过Web API或 http handler)
- ASP.NET Core文件上传与下载(多种上传方式)
- ASP.Net在web.config中设置上传文件的大小方法
- ASP.Net在web.config中设置上传文件的大小方法
- ASP.Net中设置web.config文件上传大文件方法
- 在ASP.NET Core Web API 项目里无法访问(wwwroot)下的文件
- 循序渐进学.Net Core Web Api开发系列【5】:文件上传
- sql server 关于表中只增标识问题 C# 实现自动化打开和关闭可执行文件(或 关闭停止与系统交互的可执行文件) ajaxfileupload插件上传图片功能,用MVC和aspx做后台各写了一个案例 将小写阿拉伯数字转换成大写的汉字, C# WinForm 中英文实现, 国际化实现的简单方法 ASP.NET Core 2 学习笔记(六)ASP.NET Core 2 学习笔记(三)
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志
- asp.net core webapi项目配置全局路由的方法示例