【问题标题】:java - Download and then write image as servlet responsejava - 下载然后将图像写入 servlet 响应
【发布时间】:2012-10-30 19:22:43
【问题描述】:

如何从服务器下载图像,然后将其作为响应写入我的 servlet。 保持良好性能的最佳方法是什么?

这是我的代码:

JSONObject imageJson;
... //getting my JSON
String imgUrl = imageJson.get("img");

【问题讨论】:

    标签: java json performance spring servlets


    【解决方案1】:

    完整的解决方案:下载地图并保存到文件。

        String imgUrl = "http://maps.googleapis.com/maps/api/staticmap?center=-15.800513,-47.91378&zoom=11&size=200x200&sensor=false";
        InputStream is = new URL(imgUrl).openStream();
        File archivo = new File("c://temp//mapa.png");
        archivo.setWritable(true);
        OutputStream output = new FileOutputStream(archivo);
        IOUtils.copy(is, output);
        IOUtils.closeQuietly(output);
        is.close();
    

    【讨论】:

      【解决方案2】:

      避免在 servlet 中对图像进行中间缓冲很重要。相反,只需将收到的任何内容流式传输到 servlet 响应:

      InputStream is = new URL(imgUrl).openStream();
      OutputStream os = servletResponse.getOutputStream();
      
      IOUtils.copy(is, os);
      is.close();
      

      我正在使用来自 Apache Commons 的 IOUtils(不是必需的,但很有用)。

      【讨论】:

        【解决方案3】:

        如果您不需要隐藏图像源并且服务器也可以从客户端访问,我只需将您的响应指向远程服务器(因为您已经有了 url)=> 您不需要先下载到你的服务器,但可能客户端可以直接访问它=>你不会浪费你的资源。

        但是,如果您仍然需要先将其下载到您的服务器,以下帖子可能会有所帮助:Writing image to servlet response with best performance

        【讨论】:

          猜你喜欢
          • 2011-02-28
          • 2011-12-06
          • 2020-06-03
          • 2013-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多