1

I wrote a Restful webservice with MongoDB. This is my code :

@GET
@Path("/download/{id}/")
@Produces("application/epub")
public Response getImagefile(@PathParam("content") String content,
        @PathParam("id") String imageID) throws UnknownHostException, IOException {
    String urlContent = "D:\\NetbeansWorkspace\\Webservice\\web\\download\\image.jpg";
    GridFSDBFile findImage;
        DB db = getConnection().getDB(content);
        GridFS gfsImage = new GridFS(db, "image");
        findImage = gfsImage.findOne(new ObjectId(imageID));
        findImage.writeTo(urlContent);
        File file = new File(urlContent);
        ResponseBuilder response = Response.ok((Object) urlContent);
        response.header("Content-Disposition",
                "attachment; filename=" + "image.jpg");
        return response.build();

}

I am extracting an image from a server and providing a link to it for a download. This code does this not very efficiently by saving it to urlContent (my local file) first and then making it available for download. I would like to skip saving to urlContent part and provide a link which extracts and downloads a blob image directly from the server. How can I do it?

Farid Valiyev
  • 203
  • 5
  • 20

2 Answers2

0

This question has a good example on how to do it, although it is about pdf files (it shouldn't make any difference). In a nutshell, the service should return a StreamingOutput, which is basically a wrapper around an OutputStream.

In this answer there is an even more complete example, which uses the StreamingOutput as the entity of a Response.

Community
  • 1
  • 1
francesco foresti
  • 2,004
  • 20
  • 24
0

FIXED

@GET
@Path("/download/{id}/")
@Produces("application/epub")
public Response getImagefile(@PathParam("content") String content,
        @PathParam("id") String imageID) throws UnknownHostException, IOException {

        GridFSDBFile findImage;
        DB db = getConnection().getDB(content);
        GridFS gfsImage = new GridFS(db, "image");
        findImage = gfsImage.findOne(new ObjectId(imageID));
        String filename = findImage.getFilename();
        ResponseBuilder response = Response.ok((Object) findImage.getInputStream());
        response.header("Content-Disposition",
                "attachment; filename=" + filename+".jpg");
        return response.build();

}
Farid Valiyev
  • 203
  • 5
  • 20