Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 494
prince Avatar asked Mar 24 '14 09:03

prince


1 Answers

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()
        }
    }
}
like image 183
Alden Avatar answered Sep 20 '22 01:09

Alden