Jersey REST服务更改了多部分请求的字节

时间:2018-04-09 19:49:33

标签: java tomcat jersey multipartform-data jersey-2.0

我有使用Jersey 2.25.1的REST服务,在Tomcat 7上运行。我使用Jersey的FormDataMultiPart类来接受文件上传。我可以完全接收文件,但不是文本(或xml等)的文件将其部分字节更改为Unicode替换字符。我已经尝试了各种文件(docx,pdf等),并且它们都适用于所有文件。

例如,我可以清楚地看到具有十六进制字节D2的文件正在被EF BF BD(ascii�)替换。其他字节也被替换。这显然会破坏文件,因此在通过服务后无法打开它们。

我的服务:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response call(org.glassfish.jersey.media.multipart.FormDataMultiPart formDataMultiPart) {

    Response response;

    try {

        for (String attachName : formDataMultiPart.getFields().keySet()) {

            FormDataBodyPart bodyPart = formDataMultiPart.getField(attachName);
            byte[] content = bodyPart.getEntityAs(byte[].class);
            InputStream inputStream = bodyPart.getEntityAs(InputStream.class);
            try (OutputStream outputStream = new FileOutputStream(new File("c:\\temp", attachName))) {
                    IOUtils.copy(inputStream, outputStream);
            }

        }

        return Response.status(Response.Status.OK).entity("Files successfully uploaded.").build();

    }
    catch (Exception e) {
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    return response;

}

我的测试代码:

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();

FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

formDataMultiPart.bodyPart(new FileDataBodyPart("uploadTestFile1.docx",
            new File("MYFILE.docx"),
            MediaType.APPLICATION_OCTET_STREAM_TYPE));

final WebTarget target = client.target("MYURL");
final Response response = target.request().post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()));

formDataMultiPart.close();
formDataMultiPart.close();

是否与http://jersey.576304.n2.nabble.com/Multipart-Form-And-Encoding-td3931049.html

有关

提前感谢任何建议!

0 个答案:

没有答案