質問

I am creating a REST API in JAVA using RESTlet 2.0. I want to create an API call that will return an image from the database in a similar way as Facebook is doing in its Graph API.

Basically, I will do a GET to e.g.

    http://localhost:8080/myAPI/{session_id}/img/p?id=1

This will then retrieve the blob data from the DB and then return the image in such a way that the user can display it like this:

    <img src="http://localhost:8080/myAPI/{session_id}/img/p?id=1">

I know that I will probably need to set the content-type in the header to Image/PNG (assuming the image is a PNG of course), but what I'm struggling with is returning the data correctly for this to work.

Any suggestions?

Thanks!

役に立ちましたか?

解決

not sure about 2.0, however in 2.2 you could use something like this:

@Get
public Representation getImage() {

    ...
    byte[] data = ...

    ObjectRepresentation<byte[]> or=new ObjectRepresentation<byte[]>(data, MediaType.IMAGE_PNG) {
        @Override
        public void write(OutputStream os) throws IOException {
            super.write(os);
            os.write(this.getObject());
        }
    };

    return or; 
}

他のヒント

Using 2.2 there is a ByteArrayRepresentation type.

@Get("image/jpeg")
public void getIcon() {
    byte[ ] your_images_bytes = ...
    ByteArrayRepresentation bar 
        = new ByteArrayRepresentation(your_images_bytes, MediaType.IMAGE_JPEG) ;
    getResponse().setEntity(bar);
}

In my App I am returning a byte array from my REST method. and the content-type is image/png as you have mentioned.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top