users@jersey.java.net

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

From: Kevin Duffey <andjarnic_at_yahoo.com>
Date: Tue, 7 Sep 2010 17:18:04 -0700 (PDT)

Hi all, Craig. Glad to see you're still part of this list. :)

I like what you say, although I thought you built the add-on that I was looking for on handling file upload/download.. which the link seems to be broken right now on the jersey site to get to downloads.

Anyway, the issue I have is that the XML sent in may include several values at once, not just an image (or file). I thought that I could get away with wrapping it in a CDATA block... I've not personally experienced on how to turn a chunk of perhaps base64 encoded (or binhex) binary data from a CDATA chunk, especially via a Jersey call. But it would allow me to accept a chunk of XML that contains multiple values. It doesn't have to be this way, it would just make it more in line with the rest of how my XSD works. For that matter, can you even specify an XSD element that pertains to binary data and have it work with the Jersey/JAXB, so that I can accept it via a method in that manner?



--- On Tue, 9/7/10, Craig McClanahan <craigmcc_at_gmail.com> wrote:

From: Craig McClanahan <craigmcc_at_gmail.com>
Subject: Re: [Jersey] Working with binary files (images/files, etc) via REST
To: users_at_jersey.dev.java.net
Date: Tuesday, September 7, 2010, 3:23 PM



On Tue, Sep 7, 2010 at 2:54 PM, Kevin Duffey <andjarnic_at_yahoo.com> wrote:


I went to the site today to try to find the addons to jersey.. want to look at working with sending binary data like files/images via a REST call. The downloads links all seem to go to Chapter 7 Dependencies now.

Anyway, despite that being broken, has anyone worked with sending files, images, large binary data, up via REST? I know Craig wrote an addon a while ago, just curious with all the changes lately if anyone has an elegant solution to sending files to REST and vice versa, getting files back from REST.

Thanks.


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")


        @GET
        @Produces("image/png")
        public Response download(...) {
            InputStream stream = ... InputStream pointing at my image data ...

        }

        @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.

Craig