1. 程式人生 > >阿里雲伺服器 雲物件儲存OOS(二) ---圖片上傳與讀取demo

阿里雲伺服器 雲物件儲存OOS(二) ---圖片上傳與讀取demo

上一篇講解了無需程式碼操作的阿里OOS雲物件儲存

http://blog.csdn.net/u014520797/article/details/53945912

1、SDK下載,不下載也可以,文章最後有demo,demo裡面有jar包

https://help.aliyun.com/document_detail/31947.html?spm=5176.8041989.303605.24.voFC4A

2、demo結構

 

3、前期準備工作

如果你選擇的也是華南1 ,那麼endpoint不需要變動,後面三個accessKeyId,accessKeySecret,bucketName需要你自己準備。

4、endpoint

 

5、accessKeyId,accessKeySecret位置的在個人中心頁的右上角,將滑鼠放置賬號上即可看到

建立accessKeyId

 

 

7、主要程式碼

  1. package com.kp.alioos;

  2.  
  3. import java.io.File;

  4. import java.io.FileInputStream;

  5. import java.io.InputStream;

  6. import java.net.HttpURLConnection;

  7. import java.net.URL;

  8.  
  9.  
  10.  
  11.  
  12. import com.aliyun.oss.OSSClient;

  13. import com.aliyun.oss.model.ObjectMetadata;

  14. import com.aliyun.oss.model.PutObjectResult;

  15.  
  16. /**

  17. * @author: py

  18. * @version:2016年12月29日 下午1:54:35

  19. * com.kp.alioos.OOSManager.java

  20. * @Desc

  21. */

  22. public class OOSManager {

  23. /***下載媒體檔案*/

  24. public static String DOWNLOAD_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";

  25.  
  26. /**

  27. * @date 2016年12月29日下午3:12:33

  28. * @param accessToken

  29. * @param mediaId

  30. * @param subPath askid提問id

  31. * @throws Exception String

  32. * @Des:上傳微信圖片至阿里OOS

  33. */

  34. public static String uploadWXImage(String accessToken,String mediaId,String subPath) throws Exception{

  35.  
  36. String key = OSSConfigure.remoteFilePath+subPath+"/"+subPath+"_"+mediaId;

  37. if (subPath==null) {

  38. key = OSSConfigure.remoteFilePath+OSSConfigure.subPath_null+"/"+"_"+mediaId;

  39. }

  40. String requestUrl = DOWNLOAD_MEDIA_URL;

  41. requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);

  42. System.out.println(requestUrl);

  43. try {

  44. URL url = new URL(requestUrl);

  45. HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  46. conn.setDoInput(true);

  47. conn.setRequestMethod("GET");

  48. String contentType = conn.getHeaderField("Content-Type");

  49. // 根據內容型別獲取副檔名

  50. String fileExt = MediaUtil.getFileEndWitsh(contentType);

  51. // 將mediaId作為檔名

  52. InputStream fileContent=conn.getInputStream();

  53. //建立OSSClient例項

  54. OSSClient ossClient=new OSSClient(OSSConfigure.endpoint, OSSConfigure.accessKeyId, OSSConfigure.accessKeySecret);

  55. key=key+fileExt;

  56. PutObjectResult putObject = ossClient.putObject(OSSConfigure.bucketName, key, fileContent);

  57. System.err.println("putObjectgetETag:"+putObject.getETag());

  58. System.err.println("putObjectgetRequestId:"+putObject.getRequestId());

  59. System.err.println("putObjectgetClientCRC:"+putObject.getClientCRC());

  60. System.err.println("putObjectgetServerCRC:"+putObject.getServerCRC());

  61. return OSSConfigure.accessUrl+"/" +key;

  62.  
  63. } catch (Exception e) {

  64. String error = String.format("下載媒體檔案失敗:%s", e);

  65. System.out.println(error);

  66. return null;

  67. }

  68. }

  69.  
  70. /**

  71. * @date 2016年12月29日上午11:17:37

  72. * @param ossConfigure

  73. * @param file

  74. * @param remotePath

  75. * @throws Exception String

  76. * @Des:上傳OSS伺服器檔案

  77. */

  78. public static String uploadFile(File file,String remotePath) throws Exception{

  79. InputStream fileContent=null;

  80. fileContent=new FileInputStream(file);

  81.  
  82. OSSClient ossClient=new OSSClient(OSSConfigure.endpoint, OSSConfigure.accessKeyId, OSSConfigure.accessKeySecret);

  83. String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\","/")+"/";

  84. System.err.println("remoteFilePath:"+remoteFilePath);

  85. //建立上傳Object的Metadata

  86. ObjectMetadata objectMetadata=new ObjectMetadata();

  87. objectMetadata.setContentLength(fileContent.available());

  88. objectMetadata.setCacheControl("no-cache");

  89. objectMetadata.setHeader("Pragma", "no-cache");

  90. objectMetadata.setContentEncoding("utf-8");

  91. objectMetadata.setContentType(contentType(file.getName().substring(file.getName().lastIndexOf("."))));

  92. objectMetadata.setContentDisposition("inline;filename=" + file.getName());

  93. //上傳檔案

  94. PutObjectResult putObject = ossClient.putObject(OSSConfigure.bucketName, remoteFilePath + file.getName(), fileContent, objectMetadata);

  95.  
  96. System.err.println("putObjectgetETag:"+putObject.getETag());

  97. System.err.println("putObjectgetRequestId:"+putObject.getRequestId());

  98. System.err.println("putObjectgetClientCRC:"+putObject.getClientCRC());

  99. System.err.println("putObjectgetServerCRC:"+putObject.getServerCRC());

  100. return OSSConfigure.accessUrl+"/" +remoteFilePath + file.getName();

  101. }

  102.  
  103.  
  104.  
  105. /**

  106. * @date 2016年12月29日上午11:17:22

  107. * @param ossConfigure

  108. * @param filePath void

  109. * @Des:根據key刪除OSS伺服器上的檔案

  110. */

  111. public static void deleteFile(OSSConfigure ossConfigure,String filePath){

  112. OSSClient ossClient=new OSSClient(OSSConfigure.endpoint, OSSConfigure.accessKeyId, OSSConfigure.accessKeySecret);

  113. ossClient.deleteObject(OSSConfigure.bucketName, filePath);

  114.  
  115. }

  116.  
  117.  
  118. /**

  119. * @date 2016年12月29日上午11:17:11

  120. * @param FilenameExtension

  121. * @return String

  122. * @Des:判斷OSS服務檔案上傳時檔案的contentType

  123. */

  124. public static String contentType(String FilenameExtension){

  125. if(FilenameExtension.equals("BMP")||FilenameExtension.equals("bmp")){return "image/bmp";}

  126. if(FilenameExtension.equals("GIF")||FilenameExtension.equals("gif")){return "image/gif";}

  127. if(FilenameExtension.equals("JPEG")||FilenameExtension.equals("jpeg")||

  128. FilenameExtension.equals("JPG")||FilenameExtension.equals("jpg")||

  129. FilenameExtension.equals("PNG")||FilenameExtension.equals("png")){return "image/jpeg";}

  130. if(FilenameExtension.equals("HTML")||FilenameExtension.equals("html")){return "text/html";}

  131. if(FilenameExtension.equals("TXT")||FilenameExtension.equals("txt")){return "text/plain";}

  132. if(FilenameExtension.equals("VSD")||FilenameExtension.equals("vsd")){return "application/vnd.visio";}

  133. if(FilenameExtension.equals("PPTX")||FilenameExtension.equals("pptx")||

  134. FilenameExtension.equals("PPT")||FilenameExtension.equals("ppt")){return "application/vnd.ms-powerpoint";}

  135. if(FilenameExtension.equals("DOCX")||FilenameExtension.equals("docx")||

  136. FilenameExtension.equals("DOC")||FilenameExtension.equals("doc")){return "application/msword";}

  137. if(FilenameExtension.equals("XML")||FilenameExtension.equals("xml")){return "text/xml";}

  138. return "text/html";

  139. }

  140.  
  141.  
  142.  
  143. }

測試類

  1. package com.kp.alioos;

  2.  
  3. import java.io.File;

  4.  
  5. /**

  6. * @author: py

  7. * @version:2016年12月29日 上午11:34:50

  8. * qwy.wx.uitl.alioos.TestOOS.java

  9. * @Desc

  10. */

  11. public class TestOOS {

  12.  
  13. public static void main(String[] args) {

  14. // testWX();

  15. test1();

  16. }

  17.  
  18. /**

  19. * @date 2016年12月30日下午8:29:22 void

  20. * @Des: 測試上傳微信圖片

  21. */

  22. private static void testWX() {

  23. String accessToken="";

  24. String mediaId="";

  25. String subPath="";

  26. try {

  27. OOSManager.uploadWXImage(accessToken, mediaId, subPath);

  28. } catch (Exception e) {

  29. // TODO Auto-generated catch block

  30. e.printStackTrace();

  31. }

  32. }

  33. /**

  34. * @date 2016年12月30日下午8:29:44 void

  35. * @Des:測試上傳本地圖片

  36. */

  37. private static void test1() {

  38. try {

  39. File file = new File("E:/n2/wx_img/head.png");

  40. String uploadFile = OOSManager.uploadFile(file , "test");

  41. System.err.println("uploadFile:"+uploadFile);

  42. } catch (Exception e) {

  43. // TODO Auto-generated catch block

  44. e.printStackTrace();

  45. }

  46. }

  47.  
  48.  
  49. }

8、阿里官方案例https://help.aliyun.com/document_detail/32013.html?spm=5176.doc32009.6.659.aTGNmi

9、demo下載 http://download.csdn.net/detail/u014520797/9725893

 

原文地址:https://blog.csdn.net/u014520797/article/details/53946121?utm_source=itdadao&utm_medium=referral