.NET Core 6 MVC中JS上传文件时IFormFile始终为null的问题
.NET Core 6 MVC 文件上传参数为null的解决方法
问题根源
代码存在两个关键问题导致控制器无法接收文件:
- 手动设置了错误的
Content-Type为application/json,FormData上传需要multipart/form-data类型,且浏览器会自动处理该头的边界信息,手动设置会破坏解析逻辑。 - FormData中的键名
myFile与控制器参数名myfile大小写不一致,导致模型绑定失败。
修复步骤
移除错误的Content-Type设置
删除JS中手动添加的Content-Type: application/json头,让浏览器自动生成正确的multipart/form-data请求头。统一参数名大小写
将FormData中的键名改为与控制器参数一致的myfile,或者将控制器参数名改为myFile(两种方式任选其一即可)。
修改后的代码示例
修正后的HTML/JS代码
<h1>Upload File</h1> <div> <input type="file" id="myFile" name="myFile"> <button onclick="upload()">Upload</button> </div> <script> async function upload() { const fileInput = document.querySelector('#myFile'); const formData = new FormData(); // 统一参数名为myfile,与控制器参数一致 formData.append('myfile', fileInput.files[0]); // 移除手动设置的Content-Type头 let requestOptions = { method: 'POST', redirect: 'follow', body: formData, }; const url = `${location.protocol}//${location.host}/Training/demoupload`; console.log(url) try { await fetch(url, requestOptions) .then(response => response.json()) .then(data => { alert(data.message); }) } catch (error) { alert(error) } } </script>
修正后的C#控制器代码(保留参数名myfile)
public class TrainingController : Controller { public IActionResult Index() { return View(); } [HttpPost] // 可选:添加[FromForm]特性明确绑定来源,代码意图更清晰 public JsonResult demoupload([FromForm] IFormFile myfile) { BaseResponseModel response = new BaseResponseModel(); if (myfile == null) { response.success = false; response.message = "no file passed in"; } else { response.success = true; response.message = "file passed in"; } return Json(response); } }
补充说明
- 若不想修改JS中的键名,也可以将控制器参数名改为
myFile,模型绑定同样正常工作:public JsonResult demoupload(IFormFile myFile) [FromForm]特性为可选项,MVC控制器默认会从表单请求中绑定IFormFile类型参数,显式添加可提升代码可读性。
内容的提问来源于stack exchange,提问作者Rodney Ellis
相关产品推荐
相关产品推荐

