【问题标题】:Direct download of a blob from server从服务器直接下载 blob
【发布时间】:2015-07-03 06:32:10
【问题描述】:

我用 MongoDB 编写了一个 Restful 网络服务。这是我的代码:

@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 图像。我该怎么做?

【问题讨论】:

    标签: java mongodb blob restful-url gridfs


    【解决方案1】:

    This question 有一个很好的例子来说明如何做到这一点,尽管它是关于 pdf 文件的(它不应该有任何区别)。简而言之,服务应该返回一个StreamingOutput,它基本上是一个OutputStream 的包装器。

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

    【讨论】:

      【解决方案2】:

      已修复

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

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2017-08-11
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 2013-09-22
        • 2020-09-01
        • 2022-10-25
        • 2012-07-24
        相关资源
        最近更新 更多