我们想将一个图像文件作为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 () } }
后端的错误是"嵌套异常是org.springframework.web.multipart.MultipartException:无法解析多部分servlet请求;嵌套异常是java.io.IOException:org.apache.tomcat.util.http.fileupload.FileUploadException:请求被拒绝,因为没有找到多部分边界".
阅读本文后,我们尝试在fetch中设置边框到标题:
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 [dispatcherServlet]的Servlet.service()在上下文中,路径[]引发异常[请求处理失败; 具有根本原因的嵌套异常是java.lang.NullPointerException]
我们添加多部分边界吗?应该在哪里?也许我们一开始就错了,因为我们没有得到multipart/form-data.我们怎样才能正确地得到它?
我们只是尝试删除我们的标题,它的工作原理!
fetch("http://localhost:8910/taskCreationController/createStoryTask", { mode: 'no-cors', method: "POST", body: data }).then(function (res) { if (res.ok) { alert("Perfect! "); } else if (res.status == 401) { alert("Oops! "); } }, function (e) { alert("Error submitting form!"); });