我有一个HTML表单,需要在一个请求中将3个部分上传到现有的REST API。我似乎找不到关于如何在FormData提交上设置边界的文档。
我试图按照这里给出的例子:
How to send FormData objects with Ajax-requests in jQuery?
但是当我提交数据时,它将被拒绝与以下堆栈跟踪:
Caused by: org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found.
如何设置边界?
这是HTML / Javascript:
<script type="text/javascript"> function handleSubmit() { var jsonString = "{" + "\"userId\":\"" + document.formSubmit.userId.value + "\"" + ",\"locale\":\"" + document.formSubmit.locale.value + "\"" + "}"; var data = new FormData(); data.append('Json',jsonString); data.append('frontImage',document.formSubmit.frontImage.files[0]); data.append('backImage',document.formSubmit.backImage.files[0]); document.getElementById("sent").innerHTML = jsonString; document.getElementById("results").innerHTML = ""; $.ajax({ url:getFileSubmitUrl(),data:data,cache: false,processData: false,contentType: 'multipart/form-data',type:'POST',success:function (data,status,req) { handleResults(req); },error:function (req,error) { handleResults(req); } }); } </script>
这是表格:
<form name="formSubmit" action="#"> userId: <input id="userId" name="userId" value=""/><br/> locale: <input name="locale" value="en_US"/><br/> front Image: <input type="file" name="frontImage"/><br/> back Image: <input type="file" name="backImage"/><br/> <input type="button" onclick="handleSubmit();" value="Submit"/> </form>
提前感谢任何帮助!
解决方法
穆萨的回应很棒。将contentType设置为false确实提交了表单数据。谢谢!
这是一个有效的ajax调用:
$.ajax({ url:getFileSubmitUrl(),cache:false,processData:false,contentType:false,req) { handleResults(req); },error) { handleResults(req); } });
我也发现这段代码也有效:
var oReq = new XMLHttpRequest(); oReq.open("POST",getFileSubmitUrl()); oReq.send(data); oReq.addEventListener("error",transferComplete); oReq.addEventListener("load",transferComplete); oReq.addEventListener("abort",transferComplete); } function transferComplete(evt) { handleResults(evt.target); }