NETCORE-文件上传
NETCORE-文件上传
前端参考:https://www.cnblogs.com/1285026182YUAN/p/17967688
环境:.net6 webapi
后端接口如下
[HttpPost] [Route("UpLoadFileAsync")] public async Task<IActionResult> UpLoadFileAsync([FromForm] List<IFormFile> files) { long size = files.Sum(f => f.Length); foreach (var formFile in files) { var filePath = @"D:\UploadingFiles\" + formFile.FileName; using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } } return Ok(new { count = files.Count, size }); }
前端调用如下:
<a-button type="danger" onclick="chooseFile.click()">上传文件</a-button> <input type="file" id="chooseFile" style="display: none" multiple @change="handleFileSelect" />
handleFileSelect() { var fileInput = document.getElementById('chooseFile'); var files = fileInput.files; // let types = ['image/jpeg','application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; if (files.length > 0) { // // 判断文件类型 // if (!types.includes(file.type)) { // return; // } const formData = new FormData(); [...files].forEach((t) => formData.append('files', t)); fetch('https://localhost:7096/api/afiles/UpLoadFileAsync', { method: 'POST', body: formData, }); } else { //未选择文件 } },
注:默认有文件大小限制
可在 Program.cs 中控制
#region 大文件上传限制 builder.Services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = int.MaxValue; }); //接口请求限制 builder.Services.Configure<KestrelServerOptions>(options => { options.Limits.MaxRequestBodySize = int.MaxValue;// if don't set default value is: 30 MB }); builder.Services.Configure<FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.MultipartBodyLengthLimit = int.MaxValue; // if don't set default value is: 128 MB x.MultipartHeadersLengthLimit = int.MaxValue; }); #endregion
引用:https://www.miaokee.com/601582.html