从服务器直接下载blob

时间:2015-07-03 06:32:11

标签: java mongodb blob restful-url gridfs

我用MongoDB写了一个Restful webservice。这是我的代码:

@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();

}

我从服务器中提取图像并提供指向下载的链接。此代码通过首先将其保存到urlContent(我的本地文件)然后使其可供下载来实现这一点并不是非常有效。我想跳过保存到urlContent部分,并提供一个直接从服务器提取和下载blob图像的链接。我该怎么办?

2 个答案:

答案 0 :(得分:0)

This question有一个关于如何做的好例子,虽然它是关于pdf文件(它应该没有任何区别)。简而言之,该服务应返回StreamingOutput,它基本上是OutputStream的包装。

this answer中有一个更完整的示例,它使用StreamingOutput作为Response的实体。

答案 1 :(得分:0)

<强>固定

@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();

}