javahttpresponsemultipartentity

How extract files from response entity


I have a servlet that gives the clients many files in one request. I put files(image,pdf,...) or other data (like json,...) as byte array in the response :

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());

I get the response (in the client side) like :

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

and the body is :

    --***************<<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������������������������
���@�����

..
..
..

How can i extract data`s (images , pdf , json , ... ) from response.

please help me. thanks.


Solution

  • I use the javax.mail API.

    For test :

        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();
    
        }
    }
    

    This works good.

    Also You can use Apache FileUpload.

    for test :

        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();
    
        }
    

    Enjoy.