您的位置:首页 > 编程语言 > ASP

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

2020-07-30 15:39 495 查看 https://www.cnblogs.com/fengge

直接上干货了

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

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐