import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
/**
* 下载网络远程图片
*
* @author saber
*/
public class DownImgUtils {
private static Logger LOGGER = LoggerFactory.getLogger(DownImgUtils.class);
public static String downloadURL(String fileUrl) {
//LOGGER.info("开始执行将图片下载到本地,fileUrl:{}",fileUrl);
String fileName = "";
//获取文件名,文件名实际上在URL中可以找到
int pos = fileUrl.indexOf('?');
String newUrl = fileUrl;
if (pos > 0) {
newUrl = newUrl.substring(0, pos);
}
pos = newUrl.lastIndexOf('/');
fileName = newUrl.substring(pos + 1);
fileName = "uploadImg_" + fileName;
//这里服务器上要将此图保存的路径
String savePath = System.getProperty("java.io.tmpdir");
fileName = savePath +"/"+ fileName;
HttpURLConnection connection = null;
DataInputStream in = null;
DataOutputStream out = null;
try {
URL url = new URL(fileUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(30000);
connection.setConnectTimeout(30000);
in = new DataInputStream(connection.getInputStream());
out = new DataOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
connection.disconnect();
} catch (Exception e) {
System.out.println(e + fileUrl + savePath);
} finally {
try {
if (Objects.nonNull(out)) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (Objects.nonNull(in)) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
//LOGGER.info("结束执行将图片下载到本地,fileUrl:{}",fileUrl);
return fileName;
}
}