java 在java中从web url下载图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10702484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download image from web url in java?
提问by anoop
URL url = new URL("http://localhost:8080/Work/images/abt.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response1 = out.toByteArray();
FileOutputStream fos = new FileOutputStream("C://abt.jpg");
fos.write(response1);
fos.close();
in this code there is some error in last 3 lines
在这段代码中,最后 3 行有一些错误
SEVERE: Servlet.service() for servlet ImageDownloadServlet threw exception java.io.FileNotFoundException: C:/abt.jpg (No such file or directory)
严重:servlet ImageDownloadServlet 的 Servlet.service() 抛出异常 java.io。FileNotFoundException: C:/abt.jpg(没有那个文件或目录)
How can I solve it?
我该如何解决?
回答by CosminO
maybe try switching C:/abt.jpg
to C:\\abt.jpg
也许尝试切换C:/abt.jpg
到C:\\abt.jpg
回答by ejb_guy
Try using File.pathSeparator instead of slash.
尝试使用 File.pathSeparator 而不是斜线。
回答by ejb_guy
String filePath = request.getParameter("action");
System.out.println(filePath);
// URL url = new
// URL("http://localhost:8080/Works/images/abt.jpg");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename=icon" + ".jpg");
URL url = new URL(filePath);
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ((len = stream.read(buf)) > 0) {
outs.write(buf, 0, len);
}
outs.close();
}
回答by Frantumn
("C://abt.jpg");
("C://abt.jpg");
try reversing the slashes
尝试反转斜线
("C:\\abt.jpg");
("C:\\abt.jpg");
I looked up a example linkto a FOS to C drive example, and the demo had them the other way.
回答by anoop
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException, MalformedURLException {
String filePath = request.getParameter("action");
// String filename = "abt.jpg";
System.out.println(filePath);
URL url = new URL("http://localhost:8080/Works/images/abt.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response1 = out.toByteArray();
FileOutputStream fos = new FileOutputStream("/home/user/Downloads/abt.jpg");
fos.write(response1);
fos.close();
}
this image will be in download folder
此图片将在下载文件夹中