根据URL保存图片到本地
2022-09-22 22:48:10

步骤

  1. 创建URLConnection,根据URL,获取文件流
  2. 写入本地

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

/**
* 从url中下载图片保存到本地
* @param urlPath url路径
* @param savePath 保存路径
* @param filename 文件名(传null时可以自动生成文件名)
* @return 文件路径 (保存路径 + 文件名)
* @throws Exception
*/
public static String downloadImgByURL(String urlPath,String savePath,String filename) throws Exception {
// 构造URL
URL url = new URL(urlPath);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为3s
con.setConnectTimeout(3*1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
int randomNo=(int)(Math.random()*1000000);
//若没有传进来文件名字,则按照 时间+随机数 生成文件名字
if(filename == null || "".equals(filename)){
//filename = urlPath.substring(urlPath.lastIndexOf("/")+1,urlPath.length());//获取服务器上图片的名称
filename = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())+randomNo+".jpg";//时间+随机数防止重复
}
String fullname = sf.getPath()+"\\"+ filename ;
OutputStream os = new FileOutputStream(fullname);
String virtualPath= sf.getPath() + "\\" +filename;//存入数据库的虚拟路径
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
//System.out.println(virtualPath);
return fullname;
}