问题描述
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();