java-下载图像,然后将其作为servlet响应写入 [英] java - Download and then write image as servlet response

查看:128
本文介绍了java-下载图像,然后将其作为servlet响应写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to download an image from a server and then write it as a response in my servlet. What is the best way to do it keeping good performance?

这是我的代码:

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

推荐答案

重要的是要避免在servlet中对图像进行中间缓冲.取而代之的只是将收到的任何内容流式传输到servlet响应:

It's important to avoid intermediate buffering of image in servlet. Instead just stream whatever was received to the servlet response:

InputStream is = new URL(imgUrl).openStream();
OutputStream os = servletResponse.getOutputStream();

IOUtils.copy(is, os);
is.close();

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

I'm using IOUtils from Apache Commons (not necessary, but useful).

这篇关于java-下载图像,然后将其作为servlet响应写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆