如何使用 Ajax 发送多部分文件请求

How to sent multipart file request using Ajax

我看到这个问题的变体被问了很多,但在尝试了这里的许多建议后,我仍然无法使它正常工作。基本上,我有一个 HTML 表单,在提交时向服务器发出 POST 多部分文件请求:

<form class="resource-checkout-form" method="POST" enctype="multipart/form-data" 
        id="resourcefilecheckoutform" action="/uploadAndCheckout">
    <input type="file" name="file" id="selectyamlfile" class="filestyle"/>
</form>

更改值时(选择文件),我让表单自动提交:

$('#selectyamlfile').change(function() {
      $('#resourcefilecheckoutform').submit();
    });

到服务器上的 REST 接口:

@ApiResponses(value = { 
        @ApiResponse(code = 200, message = "Success", response = HttpMessageInformationReturnDataBean.class),
        @ApiResponse(code = 404, message = "Not Found")}) 
@RequestMapping(value = "/uploadAndCheckout", method = RequestMethod.POST)
public String singleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {

目前一切顺利,成功了,它上传了选定的文件。当我尝试通过使用 Ajax 自己执行请求来绕过表单提交重定向时,问题就来了。我更改了 HTML(删除操作):

<form class="resource-checkout-form" method="POST" enctype="multipart/form-data" 
        id="resourcefilecheckoutform">
    <input type="file" name="file" id="selectyamlfile" class="filestyle"/>
</form>

并将操作本身移动到提交表单时发生的 jquery:

$('#resourcefilecheckoutform').submit(function(e){
    e.preventDefault();
    $.ajax({
        url:'/uploadAndCheckout',
        type:'POST',
        contentType: false,
        cache: false,
        processData: false,
        data:$('#resourcefilecheckoutform').serialize(),
        success:function(){
            console.log("success");
        }
    });
}); 

它发出请求,但在服务器端它抱怨请求不是多部分请求:

org.springframework.web.multipart.MultipartException: The current request is not a multipart request

我发现的第一个建议是将 contentType 更改为 false,但我已经这样做了,但没有奏效。因此,在四处搜索后,我尝试了一些方法,首先是将 contentType 更改为 multipart:

$('#resourcefilecheckoutform').submit(function(e){
    e.preventDefault();
    $.ajax({
        url:'/uploadAndCheckout',
        type:'POST',
        contentType: 'multipart/form-data',
        cache: false,
        processData: false,
        data:$('#resourcefilecheckoutform').serialize(),
        success:function(){
            console.log("success");
        }
    });
}); 

但这导致了关于缺失边界的错误:

Caused by: java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

所以我想我应该按照其他一些线程中的建议添加边界:

$('#resourcefilecheckoutform').submit(function(e){
    e.preventDefault();
    var boundary = '--'+Math.random().toString().substr(2);
    $.ajax({
        url:'/uploadAndCheckout',
        type:'POST',
        contentType: 'multipart/form-data; boundary='+boundary,
        cache: false,
        processData: false,
        data: $('#resourcefilecheckoutform').serialize(),
        success:function(){
            console.log("success");
        }
    });
}); 

但这会导致 400 - Bad Request 错误,没有其他实际反馈表明它不喜欢什么。我觉得我正在绕着一些我只是没有看到的根本错误跳舞,也许我抓取的数据本身是错误的?有谁知道如何做到这一点?

重点是这个……

data: new FormData($('#resourcefilecheckoutform')[0]),