首页 文章

Postman使用jersey 2.0投掷400 Bad for multipart / form-data image upload

提问于
浏览
2

请求:

网址:http://localhost:8080/RESTfulExample/rest/file/upload方法:POST

HEADER:Content-Type:multipart / form-data

回应:

HTTP状态400 - 错误请求

相同的代码正在使用html表单,但在postman中它投掷了400个BAD REQUEST,我在google上查找解决方案并发现边界丢失,如何解决?因为我必须通过Jquery和rest客户端从移动应用程序和Web客户端等多个客户端接收文件 .

@Path("/file")
public class UploadFileService {

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) {

        try {
            String uploadedFileLocation = "/home/nash/" + fileDetail.getFileName();

            // save it
            writeToFile(uploadedInputStream, uploadedFileLocation);

            String output = "File uploaded to : " + uploadedFileLocation;
            System.out.println("File uploaded..........");

            return Response.status(200).entity(output).build();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception " + e);
            return null;
        }

    }

    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {

        try {
            OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

1 回答

  • 10

    请按以下步骤操作:

    • 添加jersey-multipart依赖项 .

    • 在您的应用程序类中(或在 web.xml 中)启用 MultipartFeature.class .

    • DO NOT 在邮递员请求中添加Content-Type标头 .

    对我来说,上述步骤有效 . 如果这对你有帮助,请告诉我 .

相关问题