IT俱乐部 ASP.NET .net core webapi 大文件上传到wwwroot文件夹的操作代码

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

1.配置staticfiles(program文件中)

 app.UseStaticFiles();

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

namespace webapi;
/// 
/// 统一数据响应格式
/// 
public class Results
{
    /// 
    /// 自定义的响应码,可以和http响应码一致,也可以不一致
    /// 
    public int Code { get; set; }
    /// 
    /// 中文消息提示
    /// 
    public string? Msg { get; set; }
    /// 
    /// 是否成功
    /// 
    public bool Success { get; set; }
    /// 
    /// 响应的数据
    /// 
    public T? Data { get; set; }
    /// 
    /// 返回的Token: 如果有值,则前端需要此这个值替旧的token值
    /// 
    public string? Token { get; set; }
    /// 
    /// 设置数据的结果
    /// 
    /// 数据
    /// 
    public static Results DataResult(T data)
    {
        return new Results { Code = 1, Data = data, Msg = "请求成功", Success = true };
    }
    /// 
    /// 响应成功的结果
    /// 
    /// 
    /// 
    public static Results SuccessResult(string msg = "操作成功")
    {
        return new Results { Code = 1, Data = default, Msg = msg, Success = true };
    }
    /// 
    /// 响应失败的结果
    /// 
    /// 
    /// 
    public static Results FailResult(string msg = "请求失败")
    {
        return new Results { Code = -1, Data = default, Msg = msg, Success = false };
    }
    /// 
    /// 参数有误
    /// 
    /// 
    /// 
    public static Results InValidParameter(string msg = "参数有误")
    {
        return new Results { Code = -1, Data = default, Msg = msg, Success = false };
    }
    /// 
    /// 获取结果
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    public static Results GetResult(int code = 0, string? msg = null, T? data = default, bool success = true)
    {
        return new Results { Code = code, Data = data, Msg = msg, Success = success };
    }
    /// 
    /// 设置token结果
    /// 
    /// 
    /// 
    public static Results TokenResult(string token)
    {
        return new Results { 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;
/// 
/// 文件上传
/// 
[ApiController]
[Route("[controller]/[action]")]
public class UploadController : ControllerBase
{
    private readonly IWebHostEnvironment _hostEnvironment;
    /// 
    /// 注入服务
    /// 
    /// 
    public UploadController(IWebHostEnvironment hostEnvironment)
    {
        _hostEnvironment = hostEnvironment;
    }
    /// 
    /// 上传文件(支持多文件/大文件500M)
    /// 
    /// 
    [HttpPost]
    [RequestFormLimits(MultipartBodyLengthLimit = 609715200)]
    [RequestSizeLimit(609715200)]
    public async Task>> UploadFile()
    {
        var request = HttpContext.Request;
        if (!request.HasFormContentType ||
            !MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) ||
            string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
        {
            return Results>.FailResult("文件类型不支持");
        }
        var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
        var section = await reader.ReadNextSectionAsync();
        List 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>.DataResult(serverFilePathList);
    }
}

5.使用postman工具测试

6.查看本地上传文件

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

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/asp-net/9477.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部