java获取网络图片上传到OSS的方法
时间:2021-01-10 11:04:55|栏目:JAVA代码|点击: 次
OSS不支持通过一个网络地址来上传图片,所以若想将网络上的图片上传到OSS上需要走点弯路。
1、通过链接将图片下载到本地的一个文件夹下面
2、用OSS上传该文件夹下的文件
3、上传完成后删除本地的文件
具体代码如下:
//获取当前项目的绝对路径
public static String getTomcatPath(){
String nowpath;
String tempdir;
nowpath=System.getProperty("user.dir");
tempdir=nowpath.replace("bin", ""); //把bin 文件夹变到 webapps文件里面
return tempdir;
}
/**
* 将图片下载下来后,上传到OSS
* @param imgLink
* @param downloadPath
* @return
* @throws Exception
*/
private String downloadImagAndUploadToOss(String imgLink,String downloadPath) throws Exception{
List<String> urlList=new ArrayList<String>();
urlList.add(imgLink);
String imgName=DateUtil.formatDate(new Date(), "yyyyMMddhhmmss")+UuidUtil.createUUID()+".jpg";
downloadPicture(urlList,downloadPath,imgName);
String key="carAlbum/"+imgName;
String imgUrl=OSSObjectAPI.genOssPicUrl(OSSObjectAPI.XI_AN_BUCKET_NAME,OSSObjectAPI.XIAN_ACCESS_ID,OSSObjectAPI.XIAN_ACCESS_KEY,
"http://oss-cn-zhangjiakou.aliyuncs.com/",downloadPath+imgName,key);
FileUtil.delete(downloadPath+imgName);
return imgUrl;
}
/**
* 传入要下载的图片的url列表,将url所对应的图片下载到本地
* @param urlList
* @throws Exception
*/
private void downloadPicture(List<String> urlList,String path,String imgName) throws Exception {
if(urlList==null||urlList.size()==0){
return;
}
URL url = null;
FileOutputStream fileOutputStream =null;
InputStream inputStream =null;
for (String urlString : urlList) {
try {
url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0");
connection.setConnectTimeout(10 * 1000);
connection.setReadTimeout(15 * 1000);
inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int length;
fileOutputStream= new FileOutputStream(path+ File.separator+ imgName);
while ((length = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
inputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
}
}
上一篇:Java单链表的实现代码
栏 目:JAVA代码
本文标题:java获取网络图片上传到OSS的方法
本文地址:http://www.codeinn.net/misctech/43142.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




