根据图片访问url 下载到本地磁盘中,并根据当前时间生成相应的文件夹
/**
* 图片的url,将图片下载在对应的文件中
* @param urlString 图片的url
* @return
*/
public static String download(String urlString) {
String newFileUrl = null;
URL url = null;
// 打开连接
URLConnection con = null;
try {
url = new URL( urlString );
con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout( 5 * 1000 );
// 输入流
DataInputStream dataInputStream = new DataInputStream( url.openStream() );
String dPath = " C:/uploadfile/ceshi";
//图片路径公共类
newFileUrl=addressPublic(dPath);
FileOutputStream fileOutputStream = new FileOutputStream( new File(dPath + newFileUrl ) );
ByteArrayOutputStream output = new ByteArrayOutputStream();
// 1K的数据缓冲
byte[] buffer = new byte[1024];
// 读取到的数据长度
int length;
while ((length = dataInputStream.read( buffer )) > 0) {
output.write( buffer, 0, length );
}
fileOutputStream.write( output.toByteArray() );
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newFileUrl;
}
/**
*上传图片的公共路径
* @param dPath
*/
public static String addressPublic(String dPath) {
String newFileUrl=null;
// 新的图片文件名 = 编号 +"."图片扩展名
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String format = simpleDateFormat.format( date );
String[] split = format.split( "/" );
String urle= "";
for (int i = 0; i < split.length; i++) {
urle += split[i] + "/";
File file = new File( dPath + urle );
//判断文件夹是否存在
if (!file.exists() && !file.isDirectory()) {
//不存在的话,创建文件夹
file.mkdirs();
}
}
//截取老文件名的后缀
String uuid = UUID.randomUUID().toString()+ "";
//返回地址信息
newFileUrl = format +"/"+ uuid + "." + "jpg";
return newFileUrl;
}