java獲取網(wǎng)絡(luò)圖片上傳到OSS的方法
更新時間:2018年10月23日 09:13:20 作者:李秀才
這篇文章主要為大家詳細介紹了java獲取網(wǎng)絡(luò)圖片上傳到OSS,具有一定的參考價值,感興趣的小伙伴們可以參考一下
OSS不支持通過一個網(wǎng)絡(luò)地址來上傳圖片,所以若想將網(wǎng)絡(luò)上的圖片上傳到OSS上需要走點彎路。
1、通過鏈接將圖片下載到本地的一個文件夾下面
2、用OSS上傳該文件夾下的文件
3、上傳完成后刪除本地的文件
具體代碼如下:
//獲取當(dāng)前項目的絕對路徑 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所對應(yīng)的圖片下載到本地 * @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(); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot解析JSON數(shù)據(jù)的三種方案
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,易于人閱讀和編寫,同時也易于機器解析和生成,本文給大家介紹了SpringBoot解析JSON數(shù)據(jù)的三種方案,需要的朋友可以參考下2024-03-03Java 將List中的實體類按照某個字段進行分組并存放至Map中操作
這篇文章主要介紹了Java 將List中的實體類按照某個字段進行分組并存放至Map中操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10SpringBoot登錄、退出、獲取用戶信息的session處理方案
這篇文章主要介紹了SpringBoot登錄、退出、獲取用戶信息的session處理,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08SpringBoot+MybatisPlus+Mysql+Sharding-JDBC分庫分表
本文主要介紹了SpringBoot+MybatisPlus+Mysql+Sharding-JDBC分庫分表,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03