在成功的FormData POST请求上获取“ 404 Not Found”

时间:2019-04-20 08:25:05

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

这可能很简单,但是我现在真的无法解决这个问题。
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”
答案here提示将contentType更改为“ multipart / form-data”的明显解决方案失败,并在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

2 个答案:

答案 0 :(得分:-1)

var formData = {
    'entityIds', $('#theDialog').data('brp').selectedEntityIds,
    'description', $("#description").val(),
    'modeIds', $('select#otherEntityIds').val()
}

或尝试使用@ModelAttribute接收数据

答案 1 :(得分:-1)

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

来获取它们