Java調用阿里雲OSS下載文件


參考:https://blog.csdn.net/haiyanghan/article/details/106771047

阿里雲官方指導:https://help.aliyun.com/document_detail/84822.html

1、准備工作

  具體細節參考https://blog.csdn.net/haiyanghan/article/details/106771047

2、項目需求

  我這里只需要根據文件名稱把文件從oss下載下來即可,參考阿里雲官網指導:https://help.aliyun.com/document_detail/84822.html

  首先需要引入阿里雲的依賴包,如下所示:

1 <!--阿里雲oss -->
2 <dependency>
3     <groupId>com.aliyun.oss</groupId>
4     <artifactId>aliyun-sdk-oss</artifactId>
5     <version>3.10.2</version>
6 </dependency>

  如果只是想將oss文件下載到服務器的磁盤里面,可以使用下面的案例。需要注意的就是OSS的文件目錄下面的文件,指定下載路徑的時候一定要寫正常,不然會報NoSuchKey的異常信息。

 1 package com.controller;
 2 
 3 import java.io.File;
 4 
 5 import org.slf4j.Logger;
 6 import org.slf4j.LoggerFactory;
 7 import org.springframework.beans.factory.annotation.Value;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 import com.aliyun.oss.OSS;
13 import com.aliyun.oss.OSSClientBuilder;
14 import com.aliyun.oss.model.GetObjectRequest;
15 import com.aliyun.oss.model.OSSObject;
16 
17 @Controller
18 @RequestMapping(value = "/oss")
19 public class ServiceMattersOSSController {
20 
21     // 日志記錄器
22     private static final Logger logger = LoggerFactory.getLogger(ServiceMattersOSSController.class);
23 
24     // 地域節點
25     @Value("${aliyun.oss.file.endpoint}")
26     private String endpoint;
27 
28     // 創建accesskey生成的keyid
29     @Value("${aliyun.oss.file.keyid}")
30     private String accessKeyId;
31 
32     // 創建accesskey生成的secret
33     @Value("${aliyun.oss.file.keysecret}")
34     private String accessKeySecret;
35 
36     // 創建bucket時輸入的名稱
37     @Value("${aliyun.oss.file.bucketname}")
38     private String bucketName;
39 
40     // 阿里雲OSS規范,Object絕對路徑名前面不需要加斜杠
41     @Value("${aliyun.oss.file.folder}")
42     private String folder;
43 
44     /**
45      * 下載文件到本地路徑
46      * 
47      * fwsx庫的clwj字段取字段。
48      * 
49      * @param fileName
50      */
51     @RequestMapping(value = "/downOSSFileLocal")
52     @ResponseBody
53     public void downOSSFileLocal(String fileName) {
54      // 創建OSSClient實例
56         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
57
59         OSSObject object = ossClient.getObject(bucketName, folder + fileName);63         // 下載Object到本地文件,並保存到指定的本地路徑中。如果指定的本地文件存在會覆蓋,不存在則新建。
64         // 如果未指定本地路徑,則下載后的文件默認保存到示例程序所屬項目對應本地路徑中。
65         ossClient.getObject(new GetObjectRequest(bucketName, folder + fileName),
66                 new File("/data/apache/apache-tomcat-9.0.36/webapps/" + fileName));
67         // 關閉OSSClient。
68         ossClient.shutdown();70     }
71 
72 }

  如果只是想將oss文件響應給前端瀏覽器,可以使用下面的案例。

  1 package com.controller;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.File;
  5 import java.io.IOException;
  6 import java.io.OutputStream;
  7 
  8 import javax.servlet.http.HttpServletResponse;
  9 
 10 import org.slf4j.Logger;
 11 import org.slf4j.LoggerFactory;
 12 import org.springframework.beans.factory.annotation.Value;
 13 import org.springframework.stereotype.Controller;
 14 import org.springframework.web.bind.annotation.RequestMapping;
 15 import org.springframework.web.bind.annotation.ResponseBody;
 16 
 17 import com.aliyun.oss.OSS;
 18 import com.aliyun.oss.OSSClientBuilder;
 19 import com.aliyun.oss.model.GetObjectRequest;
 20 import com.aliyun.oss.model.OSSObject;
 21 
 22 @Controller
 23 @RequestMapping(value = "/oss")
 24 public class ServiceMattersOSSController {
 25 
 26     // 日志記錄器
 27     private static final Logger logger = LoggerFactory.getLogger(ServiceMattersOSSController.class);
 28 
 29     // 地域節點
 30     @Value("${aliyun.oss.file.endpoint}")
 31     private String endpoint;
 32 
 33     // 創建accesskey生成的keyid
 34     @Value("${aliyun.oss.file.keyid}")
 35     private String accessKeyId;
 36 
 37     // 創建accesskey生成的secret
 38     @Value("${aliyun.oss.file.keysecret}")
 39     private String accessKeySecret;
 40 
 41     // 創建bucket時輸入的名稱
 42     @Value("${aliyun.oss.file.bucketname}")
 43     private String bucketName;
 44 
 45     // 阿里雲OSS規范,Object絕對路徑名前面不需要加斜杠
 46     @Value("${aliyun.oss.file.folder}")
 47     private String folder;
 48 
 49     /**
 50      * 下載OSS服務器的文件
 51      * 
 52      * @param fileName
 53      * @param response
 54      */
 55     @RequestMapping(value = "/downOSSFile")
 56     @ResponseBody
 57     public void downOSSFile(String fileName, HttpServletResponse response) { 59         BufferedInputStream input = null;
 60         OutputStream outputStream = null;
 61         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); 64         OSSObject ossObject = ossClient.getObject(bucketName, folder + fileName); 68         try {
 69             response.reset();
 70             response.setCharacterEncoding("utf-8");
 71             response.setContentType("application/x-msdownload");
 72             response.addHeader("Content-Disposition",
 73                     "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
 74 
 75             input = new BufferedInputStream(ossObject.getObjectContent());
 76             byte[] buffBytes = new byte[1024];
 77             outputStream = response.getOutputStream();
 78             int read = 0;
 79             while ((read = input.read(buffBytes)) != -1) {
 80                 outputStream.write(buffBytes, 0, read);
 81             }
 82             outputStream.flush();
 83             // 數據讀取完成后,獲取的流必須關閉,否則會造成連接泄漏,導致請求無連接可用,程序無法正常工作。
 84             ossObject.close();
 85         } catch (IOException ex) {
 86             ex.printStackTrace();
 87         } finally {
 88             try {
 89                 if (outputStream != null) {
 90                     outputStream.close();
 91                 }
 92                 if (input != null) {
 93                     input.close();
 94                 }
 95             } catch (IOException e) {
 96                 e.printStackTrace();
 97             }
 98         }
 99         ossClient.shutdown();101     }
102 
103 
104 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM