【问题标题】:org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'document' is not presentorg.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文档”不存在
【发布时间】:2020-08-18 11:04:50
【问题描述】:

当我尝试发送一个很棒的文件时遇到问题。当文件小时没有问题。

控制器

@SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "newFile", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject newFile(final HttpSession session, final HttpServletResponse response,
            @RequestPart("document") final DocumentAjusteDTO dto, @RequestPart("file") final MultipartFile file)
            throws IOException {

js

    formDoc.append('file', (file.files[0]));
            var documentData = {
                tipo: tipo,
                periodo: periodo
            };
            formDoc.append('document', new Blob([JSON.stringify(documentData)], {
                type: "application/json"
            }));
var ajaxData = {
            data: formDoc,
            sendMethod: 'POST',
            target: 'new_file',
            properties: {
                contentType: false,
                processData: false
            },
            callbackSuccess: function (e) {
                ....
            }
        };
        Ajax.call(ajaxData);
    }

};

当文件小于 5mb 时。 文件 > 5mb ko

这是tomcat日志

HandlerMethod details:
Controller [com.isb.hpa.ajustes.web.controllers.AjustesController]
Method [public org.jose4j.json.internal.json_simple.JSONObject com.isb.hpa.ajustes.web.controllers.AjustesController.newFile(javax.servlet.http.HttpSession,javax.servlet.http.HttpServletResponse,com.isb.hpa.logic.rest.beans.DocumentAjusteDTO,org.springframework.web.multipart.MultipartFile) throws java.io.IOException]

org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'document' is not present
        at ....

【问题讨论】:

    标签: javascript ajax spring


    【解决方案1】:

    您的例外表明您的请求中没有“文档”。如果您的请求仅包含 MultipartFile,您可以将 required = false 添加到您的参数中:

    @RequestPart("document",  required = false) final DocumentAjusteDTO dto
    

    将这些属性添加到您的应用程序以避免文件大小错误:

    spring.servlet.multipart.max-file-size=10MB
    spring.servlet.multipart.max-request-size=12MB
    

    如果您的文件较大,请将 10 和 12 更改为更大的数字。

    另外,将以下标头添加到您的 Ajax 请求中,如 here. 所述

    headers: {
             "Content-Type": undefined
      },
    

    内容类型:未定义。这会导致浏览器将 Content-Type 设置为 multipart/form-data 并正确填充边界。手动将 Content-Type 设置为 multipart/form-data 将无法填写请求的边界参数。

    【讨论】:

    • 我需要这个文件,我只能用application.properties证明,当我在本地工作时这个问题不存在。当我尝试将其上传到服务器时,出现问题
    • 啊,这可能是因为您的端点不匹配,您的服务器等待来自 @RequestMapping(value = "newFile", ...) 的请求,您将请求发送到目标: 'new_file',将Mapping值改为new_file,如果不能解决你的问题,请提供stacktrace
    • 我有一个配置 ajax.js,我在 new_file 中转换 de newFile。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2020-04-29
    • 2019-08-23
    相关资源
    最近更新 更多