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

Nar*_*esh 2 http jersey postman

要求:

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

标题:内容类型: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();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

Agn*_*bha 10

请按以下步骤操作:

  1. 添加jersey-multipart依赖项.

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

  3. 请勿在邮递员请求中添加Content-Type标头.

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

  • 不要添加Conent-Type大量工作.为什么? (3认同)