小白使用阿里雲OSS對象存儲java版(文件上傳下載)

OSS基本概念

oss是一種用於分佈式存儲的服務,其特點是具有穩定、可靠、安全、低成本的特點。提供數據的可靠性,提供與平臺無關的RESTful API接口 。

基礎不在概述:

阿里雲官方文檔參考傳送門:https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.be1b583eeWM3AV

簡單介紹:

存儲類型(Storage Class)

OSS 提供標準、低頻訪問、歸檔三種存儲類型。

存儲空間(Bucket)

存儲空間是您用於存儲對象(Object)的容器,所有的對象都必須隸屬於某個存儲空間。

對象/文件(Object)

對象是 OSS 存儲數據的基本單元,也被稱爲 OSS 的文件。

地域(Region)

地域表示 OSS 的數據中心所在物理位置。(注:一個地域有創建bucket上限爲30個)

訪問域名(Endpoint)

Endpoint 表示 OSS 對外服務的訪問域名。

訪問密鑰(AccessKey)

AccessKey(簡稱 AK)指的是訪問身份驗證中用到的 AccessKeyId 和 AccessKeySecret。

spring boot 集成oss:

maven引入Java ossSDK:

  <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.5.0</version>
        </dependency>

創建yml文件:

aliyun:
  oss:
    access-key-secret: your accessKeySecret
    access-key-id: your accessKeyId
    endpoint: http: your endpoint 

創建config文件用於配置:

package com.springboot_oss_01.config;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/***
 *  讀取AliyunOss.yml的配置信息
 *
 * **/

@Configuration
@ConfigurationProperties("aliyun.oss")
@Data
public class AliyunOssProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
   

    @Override
    public String toString() {
        return "AliyunOssProperties{" +
                "endpoint='" + endpoint + '\'' +
                ", accessKeyId='" + accessKeyId + '\'' +
                ", accessKeySecret='" + accessKeySecret + '\'' + 
                '}';
    }

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }


    public AliyunOssProperties() {

    }
}

上述配置完成後,就可以寫上傳下載類了

ccreate  class  FileUpload.java

這裏使用的是簡單的文件上傳,上傳的方式官方有幾種,根據需求進行選擇

    // 自動注入
    @Autowired
    AliyunOssProperties aliyunOssProperties;

  public static boolean  FileUpload(File file,String BucketName){
          String endpoint=aliyunOssProperties.getEndpoint();
          String accessKeyId =aliyunOssProperties.getAccessKeyId();
          String accessKeySecret =aliyunOssProperties.getAccessKeySecret();
        // 創建OSSClient實例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String  objectName = "";
        if(file!=null){
            try {
                objectName=file.getName();
                //判斷是否有特殊字符”+“ 號 官方建議過濾這些帶有特殊字符的文件,否則會出現簽名不匹配的問題,具體請看問題總結
                if(objectName.contains("+")){
                    objectName=objectName.replaceAll("\\+","%2b");
                }
            //  String  objectNameTest ="";
            //  objectNameTest= URLEncoder.encode(objectName,"utf-8").replaceAll("%2B","%2b");
            //  objectNameTest= URLDecoder.decode(objectName,"utf-8");
            //   System.out.println(objectNameTest);
                // 上傳文件。<yourLocalFile>由本地文件路徑加文件名包括後綴組成,例如/users/local/myfile.txt。
                ossClient.putObject(BucketName, objectName,file);//("D:\\TestFile\\OSS_Flie\\RocketMQ.txt"));
                // 關閉OSSClient。
                ossClient.shutdown();
            }catch (Exception e){
                e.printStackTrace();
                return  false;
            }

        }
        //調用方法查詢文件是否存在
        return   FileExites(objectName,BucketName);
    }
    /**判斷文件是否存在*/
    public static boolean FileExites(String objectName,String bucketName){
        String endpoint=aliyunOssProperties.getEndpoint();
        String accessKeyId =aliyunOssProperties.getAccessKeyId();
        String accessKeySecret =aliyunOssProperties.getAccessKeySecret();
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 判斷文件是否存在。doesObjectExist還有一個參數isOnlyInOSS,如果爲true則忽略302重定向或鏡像;如果
        //爲false,則考慮302重定向或鏡像。
        boolean found = ossClient.doesObjectExist(bucketName, objectName);
        if(found){
            System.out.println("上傳成功!");
        }else{
            System.out.println("上傳失敗!");
        }
        System.out.println(found);
        return  found;
    }

  

文件下載:

這裏使用的是下載方式是流式下載: 可以直接放入response.getOutputStream();返回給客戶端

create class FileDownload.java

public class DownloadFiles {
    @Autowired
    AliyunOssProperties aliyunOssProperties;
    public  void downloadFile(String objectName ,String filePath, String bucketName){
          String endpoint=aliyunOssProperties.getEndpoint();
          String accessKeyId =aliyunOssProperties.getAccessKeyId();
          String accessKeySecret =aliyunOssProperties.getAccessKeySecret();

          OSSClient  ossClient= new OSSClient(endpoint, accessKeyId, accessKeySecret);
          // ossObject包含文件所在的存儲空間名稱、文件名稱、文件元信息以及一個輸入流。
          OSSObject ossObject = ossClient.getObject(bucketName, objectName);
          BufferedInputStream in=null;
        try {
            // 讀取文件內容。
            System.out.println("Object content:");
            in=new BufferedInputStream(ossObject.getObjectContent());
            byte[] buffer = new byte[1024];   
            OutputStream out =new FileOutputStream("C:\\Users\\1\\Desktop\\OssTestFiles\\4.jpg");// response.getOutputStream();
            int len = 0;
            int i=0;
            while ((len = in.read(buffer)) > 0) {
                i=i+len;
                out.write(buffer, 0, len);
            }
            System.out.println(i);
            // 數據讀取完成後,獲取的流必須關閉,否則會造成連接泄漏,導致請求無連接可用,程序無法正常工作。
            in.close();
            out.close();
            // 關閉OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

 

 

總結問題:

1、上傳文件的時候出現簽名不匹配?

答:如果上傳的文件帶有一些特殊字符如”+“ ,會出現上傳失敗,簽名不匹配的Code,出現的原因就是這些特殊字符在計算簽名的時候被轉換成了空字符串。提交工單,官方建議過濾一些帶有特殊字符的文件,儘量避免帶有特殊字符的文件上傳。

2、如何分頁查詢文件?

答:官方文檔有寫,但是不好用,如果要分頁查詢,還是用表來控制比較好。

最重要的一點:看文檔!一定要看文檔需要什麼功能就去看文檔,實在不行的就百度,如果百度也沒有,就提交工單和阿里技術支持進行溝通,能有效解決問題

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章