问题
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
SEVERE: Servlet.service() for servlet ImageDownloadServlet threw exception java.io.FileNotFoundException: C:/abt.jpg (No such file or directory)
How can I solve it?
回答1:
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();
}
回答2:
Try using File.pathSeparator instead of slash.
回答3:
maybe try switching C:/abt.jpg
to C:\\abt.jpg
回答4:
("C://abt.jpg");
try reversing the slashes
("C:\\abt.jpg");
I looked up a example link to a FOS to C drive example, and the demo had them the other way.
回答5:
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
来源:https://stackoverflow.com/questions/10702484/download-image-from-web-url-in-java