个人小结:(场景)上传图片到速卖通图片银行,需要先将图片下载到本地在进行上传
代码:
/**
* 根据图片url 下载图片到本地 返回文件路径
*/
public static String downloadUrl(String imgUrl,String filepath){
URL url = null;
try {
url = new URL(imgUrl); //可以直接使用URL类
InputStream inputStream = url.openStream(); //通过url.openStream()获取一个字节输入流
DataInputStream = new DataInputStream(inputStream);
//DataInputStream 是数据输入流。它继承于FilterInputStream。
//DataInputStream 是用来装饰其它输入流,它“允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型”。
try{
File file = new File(filepath);
if(!file.exists()){
file.mkdirs();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
filepath= filepath + imgUrl.substring(imgUrl.lastIndexOf("/")+1, imgUrl.length()); //获取图片名作为路径
FileOutputStream fileOutputStream = new FileOutputStream(new File(filepath));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}finally {
dataInputStream.close();
fileOutputStream.close(); //释放资源 建议再finally中执行
}
return filepath;
}