.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.查看本地上传文件

相关推荐
鸠摩智首席音效师14 分钟前
.NET Core 应用程序如何在 Linux 中创建 Systemd 服务 ?
linux·运维·.netcore
丨我是张先生丨5 小时前
Windows VSCode .NET CORE WebAPI Debug配置
.netcore
MoFe15 小时前
【.net core】【sqlsugar】字符串拼接+内容去重
java·开发语言·.netcore
慧都小妮子5 小时前
深入探讨 .NET Core 3.0 浮点计算差异与解决方案
.netcore·stimulsoft·.net core 3.0
眸笑丶5 小时前
.Net Core根据文件名称自动注入服务
.netcore
c_s_l_265 小时前
.net core开发windows程序在国产麒麟操作系统中运行
.netcore
咩咩觉主1 天前
尽量通俗易懂地概述.Net && U nity跨语言/跨平台相关知识
unity·c#·.net·.netcore
NetX行者3 天前
.NET 9震撼来袭:基于.NET 8的五大功能亮点,引领开发新潮流
开发语言·microsoft·c#·.netcore
小吴同学·3 天前
(实战)WebApi第13讲:怎么把不同表里的东西,包括同一个表里面不同的列设置成不同的实体,所有的给整合到一起?【前端+后端】、前端中点击标签后在界面中显示
c#·.netcore·.net core