【发布时间】:2015-05-02 07:57:07
【问题描述】:
我在 Eclipse 的资源文件夹下有一个名为 images 的文件夹。 我在图像文件夹中有多个图像。 我想通过调用网络服务在浏览器中显示所有图像。 我尝试了以下代码。我只能检索一张图片。我想要多张图片。我该怎么做?
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("images/").getPath());
final String[] EXTENSIONS = new String[]{
"png","jpg"// and other formats you need
};
// filter to identify images based on their extensions
final FilenameFilter IMAGE_FILTER = new FilenameFilter()
{
@Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
if (file.isDirectory())
{
//list of files I get
for (final File fi : file.listFiles(IMAGE_FILTER))
{
OutputStream out =null;
OutputStream out1 =null;
BufferedImage bi =null;
try
{
System.out.println("file" +fi);
//I get different files from images folder and add that to bufferedImage.
bi= ImageIO.read(fi);
response.setContentType("image/jpeg");
out= response.getOutputStream();
ImageIO.write(bi, "png", out);
ImageIO.write(bi, "jpg", out);
out.close();
}
catch (final IOException e)
{
// handle errors here
e.printStackTrace();
}
}
}
【问题讨论】:
-
可能是因为您在每次迭代中都关闭了响应输出流?
out.close()。你能把这个语句移到你的循环之外并尝试吗? -
@AniketThakur 我已经尝试过了,但仍然是同样的问题。
-
如果你想让它在普通的网络浏览器中工作,你的方法是行不通的。仅仅因为浏览器期望每个请求/响应一个图像。您需要创建一个服务/资源来创建所有文件的列表(即具有多个 IMG 标记的 HTML 响应),然后创建另一个服务,一次处理一个图像,可以从 HTML 转换路径或其他标识符进入服务器上文件所在的路径(大多数 Web 服务器已经做了这些事情)。
标签: java outputstream