【问题标题】:Getting "404 Not Found" on successful FormData POST request在成功的 FormData POST 请求上获取“404 Not Found”
【发布时间】:2019-09-10 07:20:52
【问题描述】:

这可能很简单,但我现在实在想不通。
FormData 和 File 按预期到达控制器,服务过程继续进行,没有任何异常,但在浏览器中我得到一个 Status Code: 404 Not Found 可能是什么原因?有什么想法吗?

Ajax 调用

$.ajax({
    type: 'POST',
    contentType: false,
    processData: false,
    url: '/upload-form-and-attachment/',
    data: formData,
    dataType: 'text',
    success: function(response, textStatus) {
        displayPNotifyMessage(textStatus, '<spring:message code="something.success"/>'.format([response.operationData]), 'success');
    },
    error: function($data, textStatus, errorThrown) {
        displayPNotifyMessage(textStatus, errorThrown, 'error');
    },
    complete: function(){
        closeDialog();
    }
});

formData

    var formData = new FormData();        
    formData.append('entityIds', $('#theDialog').data('brp').selectedEntityIds);
    formData.append('description', $("#description").val());
    formData.append('modeIds', $('select#otherEntityIds').val());
/*Here I append more fields to the form, and finally I append the input type file*/
    formData.append('attachment', $('input#attachment')[0].files[0]);

控制器

  @RequestMapping(value = "/upload-form-and-attachment/", method = RequestMethod.POST)
    public JSONResult uploadFormAndAttachment(
            @RequestParam("entityIds") List<Long> entityIds,
            @RequestParam("description") String description,
            @RequestParam("modeIds") List<Long> modeIds,
            MultipartHttpServletRequest request,
            HttpSession session) {          
        JSONResult jsonResult = new JSONResult();
        try {
            MultipartFile attachment = request.getFile("attachment");
            // Calling some service methods and passing them the form data
        } catch(Exception e) {
            LOGGER.error(e.getMessage());
        }       
        return jsonResult;
    }

Chrome 控制台中显示的请求标头

POST /***/upload-form-and-attachment/ HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 27274
Accept: text/plain, */*; q=0.01
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJqb7gbJhzfXRBRX7
Referer: http://localhost:8080/****
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=*******

Chrome 控制台中的响应标头

Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Content-Language: en
Content-Type: text/html;charset=UTF-8
Date: Sat, 20 Apr 2019 05:24:22 GMT
Expires: Sat, 6 May 1995 12:00:00 GMT
Pragma: no-cache
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block

将 contentType 更改为“multipart/form-data”
将 contentType 更改为“multipart/form-data”作为答案here 建议的明显解决方案失败并在 API 中产生以下错误

org.springframework.web.multipart.MultipartException: 
Failed to parse multipart servlet request; 
nested exception is org.apache.commons.fileupload.FileUploadException: 
the request was rejected because no multipart boundary was found

将 contentType 更改为 'application/x-www-form-urlencoded'
使用此内容类型会导致 API 中出现以下错误,因为整个请求显然是“字符串化”的,并且 API 无法识别传递的参数。

org.springframework.web.bind.MissingServletRequestParameterException:  
Required List parameter 'entityIds' is not present

【问题讨论】:

    标签: java spring rest spring-boot spring-restcontroller


    【解决方案1】:
    var formData = {
        'entityIds', $('#theDialog').data('brp').selectedEntityIds,
        'description', $("#description").val(),
        'modeIds', $('select#otherEntityIds').val()
    }
    

    或尝试使用@ModelAttribute 接收数据

    【讨论】:

    • 嗨,你能解释一下这到底有什么帮助吗?您是否建议将 FormData 替换为 Object?
    • 我不认为这是问题所在,您也可以编辑此答案而不是发布新答案。
    【解决方案2】:
    var formData= new FormData($('form#form_name')[0]);
    
    $.ajax({
        type: 'POST',
        url: '/upload-form-and-attachment/',
        data: formData,
        success: function(response, textStatus) {
            displayPNotifyMessage(textStatus, '<spring:message code="something.success"/>'.format([response.operationData]), 'success');
        },
        error: function($data, textStatus, errorThrown) {
            displayPNotifyMessage(textStatus, errorThrown, 'error');
        },
        complete: function(){
            closeDialog();
        }
    });
    

    创建一个与您的 formData 具有相同字段的类,然后您可以使用 @ModelAttribute 获取它们

    【讨论】:

    • 在这种情况下 ContentType 和 ProcessType 应该是什么?你试过这种方法吗?
    猜你喜欢
    • 2021-03-31
    • 2023-03-05
    • 1970-01-01
    • 2023-03-05
    • 2021-11-04
    • 2015-01-04
    • 2016-01-01
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多