.net7Mvc项目中文件上传大小限制问题

问题描述

ASP.NETCore MVC中,文件上传的最大上传文件默认为20MB

解决方案:

配置 Kestrel 服务器以允许大文件上传
下面是完整demo

@{
    ViewData["Title"] = "Home Page";
}

@* <div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <form method="post" enctype="multipart/form-data" asp-action="UploadFile">
        <input type="file" name="file" />
        <button type="submit">Upload</button>
    </form>
</div>
 *@

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload</title>
    <!-- 引入 Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <!-- 引入 Element UI -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui@2.15.7/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui@2.15.7/lib/index.js"></script>
</head>
<body>
    <div id="app">
        <el-upload class="upload-demo"
                   action="/Home/UploadFile"
                   :on-success="handleSuccess"
                   :on-error="handleError"
                   :limit="1"
                   :http-request="uploadFile"
                   multiple
                   :show-file-list="false">
            <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
        <p>{{ message }}</p>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    message: ''
                }
            },
            methods: {
                uploadFile(request) {
                    let formData = new FormData();
                    formData.append("file", request.file);

                    fetch(request.action, {
                        method: 'POST',
                        body: formData
                    })
                        .then(response => response.json())
                        .then(result => {
                            this.handleSuccess(result, request.file);
                        })
                        .catch(error => {
                            this.handleError(error, request.file);
                        });
                },
                handleSuccess(result, file) {
                    this.message = `File "${file.name}" uploaded successfully!`;
                },
                handleError(error, file) {
                    this.message = `Error uploading file "${file.name}".`;
                }
            }
        })
    </script>
</body>
</html>

        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return Content("No file selected.");
            }

            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", file.FileName);
            Directory.CreateDirectory(Path.GetDirectoryName(path));  // 确保目录存在

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return RedirectToAction("Index");
        }
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);


// 配置 Kestrel 以支持大文件上传
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = null; // 设置为 null 以允许无限制的请求体大小
});

builder.Services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = long.MaxValue; // 设置最大长度限制,适用于大文件
    options.MultipartHeadersLengthLimit = int.MaxValue;
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值