2
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();

在这段代码中,最后 3 行有一些错误

严重:servlet ImageDownloadServlet 的 Servlet.service() 引发 java.io 异常。FileNotFoundException : C:/abt.jpg (没有这样的文件或目录)

我该如何解决?

4

5 回答 5

3

也许尝试切换C:/abt.jpgC:\\abt.jpg

于 2012-05-22T13:02:42.460 回答
3

尝试使用 File.pathSeparator 而不是斜杠。

于 2012-05-22T13:14:56.880 回答
3
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();
    }
于 2012-06-15T04:07:09.140 回答
2

("C://abt.jpg");

尝试反转斜线

("C:\\abt.jpg");

我查找了一个指向FOS 到 C 驱动器示例的示例链接,而演示则以另一种方式展示了它们。

于 2012-05-22T13:03:23.420 回答
0
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();

    }

此图像将在下载文件夹中

于 2012-05-22T13:39:30.633 回答