根据URL下载图片至客户端、服务器实例

时间:2021-11-01 13:54:24

1、保存至服务器

  根据路径保存至项目所在服务器上。

         String imgUrl="";//图片地址
try {
// 构造URL
URL url = new URL(imgUrl);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream("c:\\image.jpg");//保存路径
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

2、保存至本地

  以浏览器下载的方式保存至本地。

         String imgUrl="";//URL地址
String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1);
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
URL url = new URL(imgUrl);
this.getServletResponse().setContentType("application/x-msdownload;");
this.getServletResponse().setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
this.getServletResponse().setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));
is = new BufferedInputStream(url.openStream());
os = new BufferedOutputStream(this.getServletResponse().getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
os.write(buff, 0, bytesRead);
}
if (is != null)
is.close();
if (os != null)
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}