.net core webapi 大文件上传到wwwroot文件夹
2023-12-23 06:06:25
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工具测试
6.查看本地上传文件
文章来源:https://blog.csdn.net/qq_41942413/article/details/135164047
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!