.net core webapi 大文件上传到wwwroot文件夹的操作代码

2024-03-01 0 706

1.配置staticfiles(program文件中)

app.UseStaticFiles();

2.在wwwroot下创建upload文件夹3.返回结果封装

namespace webapi;
/// <summary>
/// 统一数据响应格式
/// </summary>
public class Results<T>
{
/// <summary>
/// 自定义的响应码,可以和http响应码一致,也可以不一致
/// </summary>
public int Code { get; set; }
/// <summary>
/// 中文消息提示
/// </summary>
public string? Msg { get; set; }
/// <summary>
/// 是否成功
/// </summary>
public bool Success { get; set; }
/// <summary>
/// 响应的数据
/// </summary>
public T? Data { get; set; }
/// <summary>
/// 返回的Token: 如果有值,则前端需要此这个值替旧的token值
/// </summary>
public string? Token { get; set; }
/// <summary>
/// 设置数据的结果
/// </summary>
/// <param name=\”data\”>数据</param>
/// <returns></returns>
public static Results<T> DataResult(T data)
{
return new Results<T> { Code = 1, Data = data, Msg = \”请求成功\”, Success = true };
}
/// <summary>
/// 响应成功的结果
/// </summary>
/// <param name=\”msg\”></param>
/// <returns></returns>
public static Results<T> SuccessResult(string msg = \”操作成功\”)
{
return new Results<T> { Code = 1, Data = default, Msg = msg, Success = true };
}
/// <summary>
/// 响应失败的结果
/// </summary>
/// <param name=\”msg\”></param>
/// <returns></returns>
public static Results<T> FailResult(string msg = \”请求失败\”)
{
return new Results<T> { Code = -1, Data = default, Msg = msg, Success = false };
}
/// <summary>
/// 参数有误
/// </summary>
/// <param name=\”msg\”></param>
/// <returns></returns>
public static Results<T> InValidParameter(string msg = \”参数有误\”)
{
return new Results<T> { Code = -1, Data = default, Msg = msg, Success = false };
}
/// <summary>
/// 获取结果
/// </summary>
/// <param name=\”code\”></param>
/// <param name=\”msg\”></param>
/// <param name=\”data\”></param>
/// <param name=\”success\”></param>
/// <returns></returns>
public static Results<T> GetResult(int code = 0, string? msg = null, T? data = default, bool success = true)
{
return new Results<T> { Code = code, Data = data, Msg = msg, Success = success };
}
/// <summary>
/// 设置token结果
/// </summary>
/// <param name=\”token\”></param>
/// <returns></returns>
public static Results<T> TokenResult(string token)
{
return new Results<T> { Code = 1, Data = default, Msg = \”请求成功\”, Success = true, Token = token };
}
}

4.创建一个新的控制器

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
namespace webapi.Controllers;
/// <summary>
/// 文件上传
/// </summary>
[ApiController]
[Route(\”[controller]/[action]\”)]
public class UploadController : ControllerBase
{
private readonly IWebHostEnvironment _hostEnvironment;
/// <summary>
/// 注入服务
/// </summary>
/// <param name=\”hostEnvironment\”></param>
public UploadController(IWebHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
/// <summary>
/// 上传文件(支持多文件/大文件500M)
/// </summary>
/// <returns></returns>
[HttpPost]
[RequestFormLimits(MultipartBodyLengthLimit = 609715200)]
[RequestSizeLimit(609715200)]
public async Task<Results<List<string>>> UploadFile()
{
var request = HttpContext.Request;
if (!request.HasFormContentType ||
!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) ||
string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
{
return Results<List<string>>.FailResult(\”文件类型不支持\”);
}
var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
var section = await reader.ReadNextSectionAsync();
List<string> serverFilePathList = new();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
out var contentDisposition);
if (hasContentDispositionHeader && contentDisposition!.DispositionType.Equals(\”form-data\”) &&
!string.IsNullOrEmpty(contentDisposition.FileName.Value))
{
// 获取文件后缀名
var extension = Path.GetExtension(contentDisposition.FileName.Value);
// 为文件重命名,防止文件重名
var fileName = DateTime.Now.ToString(\”yyyyMMddHHmmssfff\”) + extension;
// 文件保存的文件夹路径
var uploadPath = Path.Combine(_hostEnvironment.WebRootPath, \”upload\”);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
var fileFullPath = Path.Combine(uploadPath, fileName);
try
{
using var targetStream = System.IO.File.Create(fileFullPath);
await section.Body.CopyToAsync(targetStream);
serverFilePathList.Add(\”/upload/\” + fileName);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
section = await reader.ReadNextSectionAsync();
}
return Results<List<string>>.DataResult(serverFilePathList);
}
}

5.使用postman工具测试

.net core webapi 大文件上传到wwwroot文件夹的操作代码

6.查看本地上传文件

.net core webapi 大文件上传到wwwroot文件夹的操作代码

到此这篇关于.net core webapi 大文件上传到wwwroot文件夹的文章就介绍到这了,更多相关.net core webapi 大文件上传内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • asp.net core webapi文件上传功能的实现
  • .Net Core WebApi部署在Linux服务器上的方法
  • .Net Core WebApi部署到Windows服务器上的步骤
  • .net core webapi通过中间件获取请求和响应内容的方法
  • .Net Core WebApi的简单创建以及使用方法

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 ASP.NET .net core webapi 大文件上传到wwwroot文件夹的操作代码 https://www.u-9.cn/biancheng/aspnet/181698.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务