我们想将一个图像文件作为multipart / form发送到后端,我们尝试使用html表单获取文件并将文件作为formData发送,这里是代码
原文链接:https://www.f2er.com/react/301282.htmlexport 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("http://localhost:8910/taskCreationController/createStoryTask",headers: { "Content-Type": "multipart/form-data; boundary=AaB03x" + "--AaB03x" + "Content-Disposition: file" + "Content-Type: png" + "Content-Transfer-Encoding: binary" + "...data... " + "--AaB03x--","Accept": "application/json",function (e) { alert("Error submitting form!"); }); }
这次,后端的错误是:servlet [dispatcherServlet]的Servlet.service()在上下文中,路径[]引发异常[请求处理失败;具有根本原因的嵌套异常是java.lang.NullPointerException]
我们添加多部分边界吗?应该在哪里?
也许我们一开始就错了,因为我们没有得到multipart / form-data.我们怎样才能正确理解?