这篇文章主要为大家详细介绍了java获取网络图片上传到OSS,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
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();
}
}
} 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家。
原文链接:https://blog.csdn.net/qq_33556185/article/details/79152679
|