.Net 6 上传文件接口 文件大小报错整体配置

csharp 复制代码
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadifyFile")]
        [RequestSizeLimit(2000 * 1024 * 1024)] // 设置最大请求体大小为 100MB
        public async Task<IActionResult> UploadifyFile(IFormFile file)
        {
            try
            {
                // 文件上传逻辑
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\attachments", file.FileName);
                // 获取当前工作目录
                string extractPath = Directory.GetCurrentDirectory() + @"\wwwroot\attachments";
                if (!System.IO.File.Exists(filePath))
                {
                    await SaveFileAsync(file, filePath);
                    //if (IsCompressedFile(filePath))
                    //{
                    // 解压文件到当前目录
                    ExtractArchive(filePath, extractPath);
                    System.IO.File.Delete(filePath);
                    //}
                }
                return Ok(filePath);
            }
            catch (Exception ex)
            {

                // 日志记录异常信息
                _logger.LogError(ex, "An error occurred during file upload.");
                return Ok(ex.Message);
            }


        }
csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
//修改FormOptions(用于将读取请求正文配置为 HTTP 窗体的选项)配置
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = int.MaxValue; //每个多部分主体的长度限制,默认值约为128MB 当前为2G
    options.ValueCountLimit = int.MaxValue; //要允许的表单条目数限制,默认为 1024个 当前为2147483647个
    options.ValueLengthLimit = int.MaxValue; //单个窗体值的长度限制 大约为 4MB 当前为2G
});

//为 ASP.NET Core Kestrel Web 服务器配置选项
builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = int.MaxValue; // 默认大约为 28.6MB 当前为2G
});

//为 IIS 进程内提供配置
builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue; // 默认大约为 28.6MB 当前为2G
});
相关推荐
周杰伦fans9 小时前
C# required 关键字详解
开发语言·网络·c#
游乐码11 小时前
c#ArrayList
开发语言·c#
唐青枫12 小时前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
c#·.net
周杰伦fans12 小时前
cad文件选项卡不见了怎么办?
c#
llm大模型算法工程师weng13 小时前
Python敏感词检测方案详解
开发语言·python·c#
游乐码13 小时前
c#stack
开发语言·c#
橘子编程14 小时前
编程语言全指南:从C到Rust
java·c语言·开发语言·c++·python·rust·c#
zztfj14 小时前
C# 异步方法 async / await CancellationToken 设置任务超时并手动取消耗时处理
c#·异步
无风听海15 小时前
.NET10之C# 中的is null深入理解
服务器·c#·.net
龙侠九重天16 小时前
C# 机器学习数据处理
开发语言·人工智能·机器学习·ai·c#