无法在 Asp.Net Core 3.1 API 中上传文件

Cannot upload a file in Asp.Net Core 3.1 API

在 React 应用程序中:

const onInputFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) {
        return;
    }

    const file = files[0];
    const formData = new FormData();
    formData.append("file", file);
    
    const uri = "path/to/my/endpoint/myc/12/upload";
    const fetchOptions = {
        method: "POST",
        headers: [["Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]],
        mode: "cors",
        body: formData
    };
    
    fetch(uri, fetchOptions).then(res => console.log(res));
};

return (
    <input
        onChange={onInputFileChange}
        type="file"
        accept={".xslx"}
    />
);

我正在发送 Excel 文件。我有以下控制器:

[HttpPost("myc/{id}/upload")]
//[Consumes("multipart/form-data")] // This line is commented intentionally
public ActionResult UploadExcelFile(string id)
{
    var form = this.Request.Form; // Exception here!!!
    return Ok();
}

当我在方法中设置断点时(开始),我看到它已命中。当我在第一行更进一步时,读取 Form:

时抛出异常
System.InvalidOperationException: 'Incorrect Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

尝试我

如果我删除属性 Consumes 中的注释,我将永远无法访问该方法;相反,我得到了 415 Unsupported media Type。

尝试二

如果我将控制器的 Consumes 和请求的 Content-Type 都设置为:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,我得到相同的错误:

System.InvalidOperationException: 'Incorrect Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

尝试三

如果我这样改变控制器:

[HttpPost("myc/{id}/upload")]
//[Consumes("multipart/form-data")]
public ActionResult UploadExcelFile(string id, IFormFile file)
{
    var form = this.Request.Form;
    return Ok();
}

我收到 400 Bad Request 并且没有点击该方法。


我应该如何完成这项工作?

只需在请求中省略 Content-Type header,浏览器就会为您设置一个正确的。由于 FormData 的正确值为 Content-Type: multipart/form-data; boundary=something,您需要让浏览器为您设置有效的边界值。

const file = files[0];
const formData = new FormData();
formData.append("file", file);

const uri = "path/to/my/endpoint/myc/12/upload";
const fetchOptions = {
    method: "POST",
    mode: "cors",
    body: formData
};

fetch(uri, fetchOptions).then(res => console.log(res));