users@jersey.java.net

Re: [Jersey] Uploading files using Jersey client

From: Imran M Yousuf <imran_at_smartitengineering.com>
Date: Fri, 20 Mar 2009 10:12:32 +0600

Thanks a lot, I have got the Forms to get working as I want :) and it
seems to work quite fine and as expected. You can find the detail code
at the end of the mail. Also I made some comments in line.

On Thu, Mar 19, 2009 at 10:44 PM, Paul Sandoz <Paul.Sandoz_at_sun.com> wrote:
>
> On Mar 19, 2009, at 11:20 AM, Imran M Yousuf wrote:
>
>>           File file = new File("src/test/resources/Splash-resized.jpg");
>>           MediaType imageType = new MediaType("image", "jpeg");
>>           FormDataMultiPart part = new FormDataMultiPart();
>>           FormDataMultiPart bodyPart = part.field("file", file,
>> imageType);
>>           resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(
>>               part);
>
> Note you can already do the above as follows:
>
>    FormDataMultiPart multiPart = new FormDataMultiPart().
>        field(
>            "file",
>            new File("src/test/resources/Splash-resized.jpg"),
>            MediaType.valueOf("image/jpg")).
>        build();
>    resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(multiPart);
>
> I have just committed the following to the trunk so you can do:
>
>    FormDataMultiPart multiPart = new FormDataMultiPart().
>        field(
>
>  FormDataContentDisposition.name("file").fileName("userfile").build(),
>            new File("src/test/resources/Splash-resized.jpg"),
>            MediaType.valueOf("image/jpg")).
>        build();
>
> I might tweak the builder pattern of FormDataContentDisposition because it
> is possible to convert one of the other builder methods in to a terminated
> builder method, but the principle will remain the same.

The only thing that I wanted to avoid is creating disposition
manually. So basically what I would like to see is some like -

new FileDataBodyPart(String formParamName, java.io.File attachment,
MediaType mediaType);
new FileDataBodyPart(String formParamName, java.io.File attachment);
//Will add media type from file name

This would basically save a lot of effort. Another think I would like
see is the FileDataContentDisposition should respect "Content-Type"
header as its "getType"; what do you think?

Also what do you think about adding a detailed example of file
attachment? like the one I implemented that would explain how to
submit forms using jersey-client and use Jersey on the server side?

Also another thing I just noticed is, if FormDataContentDisposition
had been a part of JAX-RS then my resource would not have to
depend on Jersey at all and I think such portability would be
appreciated by the community, what do you think?

>
> Paul.
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>
>

/////////////////////////////SERVER CODE/////////////////////////////

    @POST
    @Path("test")
    @Consumes({MediaType.MULTIPART_FORM_DATA,
                  MediaType.APPLICATION_FORM_URLENCODED
              })
    public Response testMultipartForm(
        @FormParam("myFile") final InputStream fileStream,
        @FormParam("myFile") final FormDataContentDisposition disposition,
        @FormParam("text") final String simpleText,
        @FormParam("integer") final Integer simpleInt,
        @DefaultValue(value = "false") @FormParam("bool") final
Boolean simpleBoolean) {
        if (fileStream == null && disposition == null && simpleText == null &&
            simpleInt == null && simpleBoolean == null) {
            Response response = Response.status(Status.NOT_ACCEPTABLE).build();
            return response;
        }
        System.out.println(":::::::::::::::MULTIPART TEST!:::::::::::::::");
        long size;
        long fileSize;
        String fileName = "null";
        if (disposition != null && disposition.getSize() > 0) {
            size = disposition.getSize();
            fileSize = size;
            fileName = disposition.getFileName();
        }
        else {
            size = 100;
            fileSize = -1;
        }
        long count = 0;
        if (fileStream != null) {
            byte[] buffer = new byte[(int) size];
            try {
                int read = fileStream.read(buffer);
                do {
                    count += read;
                    read = fileStream.read(buffer);
                }
                while (read > -1);
                fileStream.close();
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("Read file " + fileName + " size: " + count +
            ", supplied file size: " + fileSize);
        System.out.println("Integer: " + simpleInt);
        System.out.println("String: " + simpleText);
        System.out.println("Boolean: " + simpleBoolean);
        Form form = new Form();
        form.add("fileName", fileName);
        form.add("fileSize", size);
        form.add("readFileSize", count);
        form.add("text", simpleText);
        form.add("integer", simpleInt);
        form.add("bool", simpleBoolean);
        Response response = Response.ok(form).build();
        return response;
    }


/////////////////////////////CLIENT CODE/////////////////////////////

    private void doFileAttachmentTest() {
        try {
            WebResource resource =
                getWebResource().path("pub-house").path("test");
            File file = new File("src/test/resources/Splash-resized.jpg");
            MediaType imageType = new MediaType("image", "jpeg");
            FormDataMultiPart part = new FormDataMultiPart();
            final String fileParamName = "myFile";
            final String intParamName = "integer";
            final String boolParamName = "bool";
            final String strParamName = "text";
            final FormDataBodyPart fileAttachmentPart =
                addFileAttachment(fileParamName, file, imageType);
            fileAttachmentPart.setParent(part);
            part.bodyPart(fileAttachmentPart);
            String sampleText1 = "sample text!";
            String sampleInt1 = "12";
            part.field(intParamName, sampleInt1).field(strParamName,
sampleText1);
            ClientResponse response = resource.type(
                MediaType.MULTIPART_FORM_DATA_TYPE).post(
                ClientResponse.class, part);
            System.out.println(response.getResponseStatus().toString());
            assertEquals(Status.OK.getStatusCode(), response.getStatus());
            Form readForm = response.getEntity(Form.class);
            assertEquals(sampleInt1, readForm.getFirst(intParamName));
            assertEquals(sampleText1, readForm.getFirst(strParamName));
            assertEquals(file.getName(), readForm.getFirst("fileName"));
            assertEquals(String.valueOf(file.length()),
                readForm.getFirst("fileSize"));
            assertEquals(String.valueOf(file.length()), readForm.getFirst(
                "readFileSize"));
            response.close();
            String sampleText2 = "sample text 2!";
            String sampleInt2 = "13";
            String sampleBool = "true";
            Form form = new Form();
            form.add(intParamName, sampleInt2);
            form.add(strParamName, sampleText2);
            form.add(boolParamName, sampleBool);
            response =
resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).
                post(ClientResponse.class, form);
            System.out.println(response.getResponseStatus().toString());
            readForm = response.getEntity(Form.class);
            assertEquals(sampleInt2, readForm.getFirst(intParamName));
            assertEquals(sampleText2, readForm.getFirst(strParamName));
            assertEquals(sampleBool, readForm.getFirst(boolParamName));
            assertEquals(Status.OK.getStatusCode(), response.getStatus());
            response.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
            fail(ex.getMessage());
        }
    }

    protected FormDataBodyPart addFileAttachment(final String fileParamName,
                                                 final File file,
                                                 final MediaType imageType) {
        FormDataBodyPart bodyPart = new FormDataBodyPart(fileParamName, file,
            imageType);
        bodyPart.getHeaders().putSingle("Content-Type", imageType.toString());
        bodyPart.getHeaders().
            putSingle("Content-Disposition",
            getContentDisposition(fileParamName, file));
        return bodyPart;
    }

    protected String getContentDisposition(String paramName,
                                           File file) {
        if (StringUtils.isBlank(paramName)) {
            throw new IllegalArgumentException();
        }
        StringBuilder builder = new StringBuilder("form-data; name=");
        builder.append(paramName);
        if (file != null) {
            builder.append("; filename=").append(file.getName());
            if (file.exists()) {
                builder.append("; size=").append(file.length());
            }
        }
        return builder.toString();
    }


-- 
Imran M Yousuf
Entrepreneur & Software Engineer
Smart IT Engineering
Dhaka, Bangladesh
Email: imran_at_smartitengineering.com
Blog: http://imyousuf-tech.blogs.smartitengineering.com/
Mobile: +880-1711402557