java获取网络图片上传到OSS的方法
OSS不支持通过一个网络地址来上传图片,所以若想将网络上的图片上传到OSS上需要走点弯路。
1、通过链接将图片下载到本地的一个文件夹下面
2、用OSS上传该文件夹下的文件
3、上传完成后删除本地的文件
具体代码如下:
//获取当前项目的绝对路径 publicstaticStringgetTomcatPath(){ Stringnowpath; Stringtempdir; nowpath=System.getProperty("user.dir"); tempdir=nowpath.replace("bin","");//把bin文件夹变到webapps文件里面 returntempdir; } /** *将图片下载下来后,上传到OSS *@paramimgLink *@paramdownloadPath *@return *@throwsException */ privateStringdownloadImagAndUploadToOss(StringimgLink,StringdownloadPath)throwsException{ ListurlList=newArrayList (); urlList.add(imgLink); StringimgName=DateUtil.formatDate(newDate(),"yyyyMMddhhmmss")+UuidUtil.createUUID()+".jpg"; downloadPicture(urlList,downloadPath,imgName); Stringkey="carAlbum/"+imgName; StringimgUrl=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); returnimgUrl; } /** *传入要下载的图片的url列表,将url所对应的图片下载到本地 *@paramurlList *@throwsException */ privatevoiddownloadPicture(List urlList,Stringpath,StringimgName)throwsException{ if(urlList==null||urlList.size()==0){ return; } URLurl=null; FileOutputStreamfileOutputStream=null; InputStreaminputStream=null; for(StringurlString:urlList){ try{ url=newURL(urlString); HttpURLConnectionconnection=(HttpURLConnection)url.openConnection(); connection.addRequestProperty("User-Agent","Mozilla/5.0(WindowsNT6.1;WOW64;rv:55.0)Gecko/20100101Firefox/55.0"); connection.setConnectTimeout(10*1000); connection.setReadTimeout(15*1000); inputStream=connection.getInputStream(); byte[]buffer=newbyte[1024]; intlength; fileOutputStream=newFileOutputStream(path+File.separator+imgName); while((length=inputStream.read(buffer))!=-1){ fileOutputStream.write(buffer,0,length); } }catch(Exceptione){ e.printStackTrace(); }finally{ inputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。