栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java获取网络图片上传到OSS的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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; 
 } 
 
 private String downloadImagAndUploadToOss(String imglink,String downloadPath) throws Exception{
  List urlList=new ArrayList();
  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;
 } 
  
 private void downloadPicture(List 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(); 
   }
  } 
 
 } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/139826.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号