我们想将图像文件作为 multipart/form 发送到后端,我们尝试使用 html 表单获取文件并将文件作为 formData 发送,这里是代码
export default class Task extends React.Component {
uploadAction() {
var data = new FormData();
var imagedata = document.querySelector('input[type="file"]').files[0];
data.append("data", imagedata);
fetch("http://localhost:8910/taskCreationController/createStoryTask", {
mode: 'no-cors',
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
"Accept": "application/json",
"type": "formData"
},
body: data
}).then(function (res) {
if (res.ok) {
alert("Perfect! ");
} else if (res.status == 401) {
alert("Oops! ");
}
}, function (e) {
alert("Error submitting form!");
});
}
render() {
return (
<form encType="multipart/form-data" action="">
<input type="file" name="fileName" defaultValue="fileName"></input>
<input type="button" value="upload" onClick={this.uploadAction.bind(this)}></input>
</form>
)
}
}
后端的错误是 “嵌套异常是 org.springframework.web.multipart.MultipartException:无法解析多部分 servlet 请求;嵌套异常是 java.io.IOException:org.apache.tomcat.util.http.fileupload.FileUploadException:请求被拒绝,因为没有找到多部分边界”。
读完 这篇 文章后,我们尝试在 fetch 中为 headers 设置边界:
fetch("http://localhost:8910/taskCreationController/createStoryTask", {
mode: 'no-cors',
method: "POST",
headers: {
"Content-Type": "multipart/form-data; boundary=AaB03x" +
"--AaB03x" +
"Content-Disposition: file" +
"Content-Type: png" +
"Content-Transfer-Encoding: binary" +
"...data... " +
"--AaB03x--",
"Accept": "application/json",
"type": "formData"
},
body: data
}).then(function (res) {
if (res.ok) {
alert("Perfect! ");
} else if (res.status == 401) {
alert("Oops! ");
}
}, function (e) {
alert("Error submitting form!");
});
}
这一次,后端的错误是: Servlet.service() for servlet [dispatcherServlet] in context with path [] throw exception [Request processing failed;嵌套异常是 java.lang.NullPointerException] 的根本原因
我们添加多部分边界对吗?它应该在哪里?也许我们一开始是错的,因为我们没有得到 multipart/form-data。我们怎样才能正确地得到它?
原文由 Yuehai 发布,翻译遵循 CC BY-SA 4.0 许可协议
我们只是尝试删除我们的标题并且它有效!