users@jersey.java.net

Re: [Jersey] Working with binary files (images/files, etc) via REST

From: Charles Overbeck <coverbec_at_pacbell.net>
Date: Tue, 14 Sep 2010 17:45:24 -0700 (PDT)

I'm just implementing the uploading myself for the first time. In addition to
the actual bytes, the only metadata I need is the name being given to those
bytes, e.g., foo.jpg, goo.doc, etc. I'm thinking that instead of having to use
the multipart extension, I could just pass the name in the HTTP header,
something like Content-Disposition: filename=foo.jpg.

Is there any reason this is a bad idea/design? I haven't tried it yet, but it
seems like it should work.

Something like:
@Context
protected HttpHeaders httpHeaders;
..

@POST
@Consumes("application/octet-stream")
public void upload(InputStream stream) {
   String name =
getFileNameFromHeader(httpHeaders.getRequestHeader("Content-Disposition"));
   // Read from stream and save bytes with name in database.
}

Thanks,

Charles

>>For upload and download of binary data by itself, the simplest thing to do is
>>accept an InputStream argument (for upload), or produce an entity that is an
>>InputStream (for download):

    @Path("/foo")
    public class MyResourceClass {

        @GET
        @Produces("image/png")
        public Response download(...) {
            InputStream stream = ... InputStream pointing at my image data ...
            return Response.ok().entity(stream).build();
        }

        @POST
        @Consumes("image/png")
        public void upload(InputStream stream) {
            ... read from stream and store the image somewhere ...
        }

This works because JAX-RS includes MessageBodyReader and MessageBodyWriter
implementations that know what to do with an InputStream.

If you want to send metadata about the image along with the image itself, you
can use the multipart extension stuff, but the same principle applies ... you'll
use an InputStream to deal with the multipart body part that contains the binary
data.<<