prince
prince

Reputation: 611

How can receive multiple files in InputStream and process it accordingly?

I want to receive the multiple files uploaded from my client-side. I uploaded multiple files and request my server-side (Java) using JAX-RS(Jersey).

I have the following code,

@POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void upload(@Context UriInfo uriInfo,
            @FormDataParam("file") final InputStream is,
            @FormDataParam("file") final FormDataContentDisposition detail) {
FileOutputStream os = new FileOutputStream("Path/to/save/" + appropriatefileName);
    byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
}

How can i write the files separately in the server side as uploaded in the client side.

For eg. I uploaded files such as My_File.txt, My_File.PNG, My_File.doc. I need to write as same as the above My_File.txt, My_File.PNG, My_File.doc in the server side.

How can I achieve this?

Upvotes: 6

Views: 6141

Answers (2)

Loki
Loki

Reputation: 276

There is a blog for the scenario you are looking for. Hope this helps http://opensourzesupport.wordpress.com/2012/10/27/multiple-file-upload-along-with-form-data-in-jax-rs/

Upvotes: 0

Alden
Alden

Reputation: 6703

You could try something like this:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void upload(FormDataMultiPart formParams)
{
    Map<String, List<FormDataBodyPart>> fieldsByName = formParams.getFields();

    // Usually each value in fieldsByName will be a list of length 1.
    // Assuming each field in the form is a file, just loop through them.

    for (List<FormDataBodyPart> fields : fieldsByName.values())
    {
        for (FormDataBodyPart field : fields)
        {
            InputStream is = field.getEntityAs(InputStream.class);
            String fileName = field.getName();

            // TODO: SAVE FILE HERE

            // if you want media type for validation, it's field.getMediaType()
        }
    }
}

Upvotes: 11

Related Questions