如何从响应实体中提取文件

How extract files from response entity

我有一个 servlet,可以在一次请求中为客户提供多个文件。 我将文件(图像、pdf、...)或其他数据(如 json、...)作为字节数组放入响应中:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ByteArrayBody pic1 = new ByteArrayBody(imageBytes1, "pic1.png");
ByteArrayBody pic2 = new ByteArrayBody(imageBytes2, "pic2.png");

builder.addPart("img1",  pic1);  
builder.addPart("img2",  pic2);  

StringBody sb = new StringBody(responseJson.toString(),ContentType.APPLICATION_JSON);

builder.addPart("projectsJson", sb);

String boundary = "***************<<boundary>>****************";
builder.setBoundary(boundary);              

HttpEntity entity = builder.build();

entity.writeTo(response.getOutputStream());

我得到的响应(在客户端)如下:

String body = EntityUtils.toString(response.getEntity());
System.out.println("body : " + body);

正文是:

    --***************<<boundary>>****************
Content-Disposition: form-data; name="pdf1"; filename="test2"
Content-Type: application/octet-stream

%PDF-1.5
%����
3 0 obj
<< /Length 4 0 R
   /Filter /FlateDecode
>>
stream
x��Zۊ��}����&�7��`����a����,��3���wDd�.]R����4�V+��q���r���r��EJ�wܝC�>��}}���}>A�?_�>\]��W߾����@��.D'��������w؝q|��ٯ�ޝw����s�z0��?&o�<׹�"z�!�7ca�)���Q�&U��nJ��@��]c@�N���}H��&��4U�0'D���~F
..
..
..


    --***************<<boundary>>****************
Content-Disposition: form-data; name="img1"; filename="fgfgf"
Content-Type: image/png

�����JFIF��H�H����o�Exif��II*��������������������������������������������(�������1��������2���������������i������Q��%������S���T��Sony�E6833�H������H������32.0.A.6.170_0_f500�2015:11:14 12:09:58������u   ������v ������x �����y  �����z  ��������,��������4��'���������������0220�����<�������P���ʿb    �����c  �����d  �����f  ������g ������h ������i ������j ������k ������l �����m  �����n  �����o  ��#���p ��*���q ��,���r ��)���s ��#���t �����u  �����v  �����w  ������x ������y ������z ������{ ������| ������~ �����   ������    �����Q������������������������
���@�����

..
..
..

我如何从响应中提取数据(图像、pdf、json、...)。

请帮帮我。 谢谢。

有可能,ApacheFileUpload会帮助你。我们在 servlet 中使用它来上传文件。

我用的是javax.mailAPI.

测试:

    ByteArrayDataSource ds = new ByteArrayDataSource (response.getEntity().getContent(), "multipart/mixed");
    MimeMultipart multipart = new MimeMultipart(ds);  
for (int i = 0; i < multipart.getCount(); i++) {
    BodyPart bodyPart = multipart.getBodyPart(i);

    System.out.println("body : " + bodyPart.getFileName());
    System.out.println("body : " + bodyPart.getContentType());

    DataHandler handler = bodyPart.getDataHandler();
    System.out.println("handler : " + handler.getName());
    System.out.println("handler : " + handler.getContentType());



    String curContentType = handler.getContentType();

    if (curContentType.equalsIgnoreCase("application/json")) {
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        handler.writeTo(arrayOutputStream);
        System.out.println("projectsJson : " + arrayOutputStream);
    } else {
        OutputStream outputStream = null;
        String ext = "";
        if (curContentType.equalsIgnoreCase("image/gif")) {
            ext = ".gif";
        } else if (curContentType.equalsIgnoreCase("image/jpeg")) {
            ext = ".jpg";
        }else if (curContentType.equalsIgnoreCase("image/png")) {
            ext = ".png";
        } else if (curContentType.equalsIgnoreCase("image/bmp")) {
            ext = ".bmp";
        } else if (curContentType.equalsIgnoreCase("application/pdf")
                || (curContentType.equalsIgnoreCase("application/x-pdf"))) {
            ext = ".pdf";
        }

        outputStream = new FileOutputStream(handler.getName()+ext);
        handler.writeTo(outputStream);
        outputStream.flush();
        outputStream.close();

    }
}

这个效果不错。

您也可以使用 Apache FileUpload。

测试:

    byte[] bodyarr = toByteArr(response.getEntity().getContent());
    byte[] boundary = "*************boundary>>****************".getBytes();

    ByteArrayInputStream bis = new ByteArrayInputStream(bodyarr);
    MultipartStream stream;

    stream = new MultipartStream(bis,boundary);     

    boolean hasNextPart = stream.skipPreamble();

    while (hasNextPart) {
        String header=stream.readHeaders();
        String name = getNameFromHeader(header);

        //if data is image 
        FileOutputStream outputStream = new  FileOutputStream(name+".png");
        stream.readBodyData(outputStream);

        hasNextPart = stream.readBoundary();

    }

尽情享受吧。