Java编写一下图片下载程序?

Python011

Java编写一下图片下载程序?,第1张

楼上的写的没错,不过感觉太麻烦了,用hutool工具包来写个方法

HttpUtil.downloadFile("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", new File("F://demo4/baidu_logo.png"))

第一个参数为百度logo图片,第二个为我本地下载位置,下载结果如图

ublic HttpServletResponse download(String path, HttpServletResponse response) {

try {

// path是指欲下载的文件的路径。

File file = new File(path)

// 取得文件名。

String filename = file.getName()

// 取得文件的后缀名。

String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase()

// 以流的形式下载文件。

InputStream fis = new BufferedInputStream(new FileInputStream(path))

byte[] buffer = new byte[fis.available()]

fis.read(buffer)

fis.close()

// 清空response

response.reset()

// 设置response的Header

response.addHeader("Content-Disposition", "attachmentfilename=" + new String(filename.getBytes()))

response.addHeader("Content-Length", "" + file.length())

OutputStream toClient = new BufferedOutputStream(response.getOutputStream())

response.setContentType("application/octet-stream")

toClient.write(buffer)

toClient.flush()

toClient.close()

} catch (IOException ex) {

ex.printStackTrace()

}

return response

}

放在 /home/image 这个目录下面, 但是这个路径是非root用户的根目录,可能会出现问题, 所以建议放在 /data/ 这个目录下面, 在这下面创建一个image目录存放文件。