.net core webapi 大文件上传到wwwroot文件夹

1.配置staticfiles(program文件中)

csharp 复制代码
 app.UseStaticFiles();

2.在wwwroot下创建upload文件夹

3.返回结果封装

csharp 复制代码
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.创建一个新的控制器

csharp 复制代码
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.查看本地上传文件

相关推荐
_oP_i1 小时前
.NET Core 项目配置到 Jenkins
运维·jenkins·.netcore
A^mber2 天前
基于.NetCore 的 AI 识别系统的设计与实现
人工智能·.netcore
Jeffrey~~4 天前
.Net_比对Json文件是否一致
c#·json·.net·.netcore
吳所畏惧5 天前
C#轻松实现Winform监控文件夹变化以及监控文件新增、修改、删除、重命名等操作保姆级详细教程
开发语言·windows·c#·.net·.netcore
CS软件开发框架5 天前
C/S软件授权注册系统-轻量级WebApi服务器介绍
运维·服务器·visualstudio·c#·.net·.netcore
鸠摩智首席音效师6 天前
如何使用 Docker 容器化 .NET Core 应用程序 ?
docker·容器·.netcore
洱海之月6 天前
.Net Core框架创建一个Windows服务类型的应用程序
.netcore
洱海之月6 天前
.Net Core配置使用Log4Net日志记录
.netcore
张3蜂6 天前
.NET Core 各版本特点、差异及适用场景详解
asp.net·.net·.netcore
dot.Net安全矩阵6 天前
.NET 技术 | 调用系统API创建Windows服务
windows·安全·web安全·矩阵·.net·.netcore