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

zynd9foi  于 2023-04-20  发布在  Postman
关注(0)|答案(1)|浏览(196)

当我尝试调用/upload上的Web服务来使用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:在部件中找不到内容处置标头
为了确保在Web服务的代码中找到正确的方法,我用返回500 Internal Server Error的return语句替换了整个方法。然而,我仍然收到了和以前一样的错误。
在控件到达/upload方法之前,似乎运行了一些其他的逻辑,我一辈子都不知道它是从哪里来的。它可能是某种装饰器,但我对Java不是很熟悉,所以任何指针都会有帮助。

**旁注:**由于我不确定是什么原因导致了这个错误,我甚至在GitHub上查看了RESTEasy的源代码。我认为这与没有正确提供Content-Disposition头有关,但我尽我所知正确提供了它。

我还尝试在multipart表单主体中提供Content-Disposition头,但这没有帮助。
如何解决此错误?

f0ofjuux

f0ofjuux1#

你在/upload调用你的网络服务时是否设置了头内容/类型?如果是,这可能是问题所在。也许你的问题与下面的问题类似
The request was rejected because no multipart boundary was found in springboot

相关问题