调试 RESTEasy 文件上传 - `org.springframework.web.multipart.MultipartException:无法解析多部分 servlet 请求`

问题描述 投票:0回答:0

当我尝试在

/upload
调用网络服务以使用 RESTEasy 上传多部分表单数据时,出现以下错误。

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

/upload
网络服务:

@POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    public Response uploadFile(MultipartFormDataInput input) {

        String fileName = "";
        
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("uploadedFile");

        for (InputPart inputPart : inputParts) {

         try {

            MultivaluedMap<String, String> header = inputPart.getHeaders();
            fileName = getFileName(header);

            //convert the uploaded file to inputstream
            InputStream inputStream = inputPart.getBody(InputStream.class,null);

            byte [] bytes = IOUtils.toByteArray(inputStream);
                
            //constructs upload file path
            fileName = UPLOADED_FILE_PATH + fileName;
                
            writeFile(bytes,fileName);
                
            System.out.println("Done");

          } catch (IOException e) {
            e.printStackTrace();
          }

        }

        return Response.status(200)
            .entity("uploadFile is called, Uploaded file name : " + fileName).build();

    }

    /**
     * header sample
     * {
     *  Content-Type=[image/png], 
     *  Content-Disposition=[form-data; name="file"; filename="filename.extension"]
     * }
     **/
    //get uploaded filename, is there a easy way in RESTEasy?
    private String getFileName(MultivaluedMap<String, String> header) {

        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
        
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {

                String[] name = filename.split("=");
                
                String finalFileName = name[1].trim().replaceAll("\"", "");
                return finalFileName;
            }
        }
        return "unknown";
    }
}

当我尝试使用 Web 服务内部的调试点对其进行调试时,调试控件不会进入 Web 服务内部。

我使用带有正确标头的 Postman 发送请求并收到以下错误作为响应:

java.lang.RuntimeException:RESTEASY007500:无法在部分中找到 Content-Dispostion 标头

为了确保我在 Web 服务代码中查看正确的方法,我用返回 500 Internal Server Error 的 return 语句替换了整个方法。这意味着我应该在调用 /upload 端点时收到 500 Internal Server 错误;然而,我仍然收到和以前一样的错误。

似乎在控件到达 /upload 方法之前运行了一些其他逻辑,我终究无法弄清楚它的来源。它可能是某种装饰器,但我对 Java 不太熟悉,所以任何指针都会有所帮助。

旁注: 由于我不确定是什么导致了这个错误,我什至查看了 GitHub 上 RESTEasy 的源代码。我认为这与未正确提供

Content-Disposition
标头有关,但据我所知我正在正确提供它。

我还尝试在多部分表单正文中提供 Content-Disposition 标头,但这没有帮助。

如何解决这个错误?

java file-upload postman multipartform-data resteasy
© www.soinside.com 2019 - 2024. All rights reserved.