一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - SpringBoot整合阿里云OSS對象存儲服務(wù)的實現(xiàn)

SpringBoot整合阿里云OSS對象存儲服務(wù)的實現(xiàn)

2020-08-11 00:06Mistra丶 Java教程

這篇文章主要介紹了SpringBoot整合阿里云OSS對象存儲服務(wù)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

今天來整合一下SpringBoot阿里云OSS對象存儲服務(wù)。

一、配置OSS服務(wù)

先在阿里云開通對象存儲服務(wù),拿到AccessKeyId、AccessKeySecret。

SpringBoot整合阿里云OSS對象存儲服務(wù)的實現(xiàn)

創(chuàng)建你的bucket(存儲空間),相當(dāng)于一個一個的文件夾目錄。按業(yè)務(wù)需求分類存儲你的文件,圖片,音頻,app包等等。創(chuàng)建bucket是要選擇該bucket的權(quán)限,私有,公共讀,公共讀寫,按需求選擇。創(chuàng)建bucket時對應(yīng)的endpoint要記住,上傳文件需要用到。

SpringBoot整合阿里云OSS對象存儲服務(wù)的實現(xiàn)

可以配置bucket的生命周期,比如說某些文件有過期時間的,可以配置一下。

SpringBoot整合阿里云OSS對象存儲服務(wù)的實現(xiàn)

二、代碼實現(xiàn)

引入依賴包

?
1
2
3
4
5
<dependency>
  <groupId>com.aliyun.oss</groupId>
  <artifactId>aliyun-sdk-oss</artifactId>
  <version>2.8.3</version>
</dependency>

配置文件application.yml

?
1
2
3
4
5
6
7
8
aliyun-oss:
 #bucket名稱
 bucketApp: xxx-app
 region: oss-cn-shenzhen
 accessKeyId: 你的accessKeyId
 accessKeySecret: 你的accessKeySecret

對應(yīng)上面配置文件的properties類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.example.file.config;
 
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
@Component
@ConfigurationProperties(prefix = "aliyun-oss")
@Data
public class AliyunOSSProperties {
 
  /**
   * 服務(wù)器地點
   */
  private String region;
  /**
   * 服務(wù)器地址
   */
  private String endpoint;
  /**
   * OSS身份id
   */
  private String accessKeyId;
  /**
   * 身份密鑰
   */
  private String accessKeySecret;
 
  /**
   * App文件bucketName
   */
  private String bucketApp;
  /**
   * App包文件地址前綴
   */
  private String domainApp;
}

上傳文件工具類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package com.example.file.utils;
 
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.example.common.exception.BusinessErrorCode;
import com.example.common.exception.BusinessException;
import com.example.common.utils.FileIdUtils;
import com.example.file.config.AliyunOSSProperties;
import com.example.file.config.FileTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
 
@Component
public class AliyunOSSUtil {
 
  @Autowired
  private AliyunOSSProperties aliyunOSSProperties;
 
  private static Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
 
  /**
   * 文件不存在
   */
  private final String NO_SUCH_KEY = "NoSuchKey";
  /**
   * 存儲空間不存在
   */
  private final String NO_SUCH_BUCKET = "NoSuchBucket";
 
  /**
   * 上傳文件到阿里云 OSS 服務(wù)器
   *
   * @param files
   * @param fileTypeEnum
   * @param bucketName
   * @param storagePath
   * @return
   */
  public List<String> uploadFile(MultipartFile[] files, FileTypeEnum fileTypeEnum, String bucketName, String storagePath, String prefix) {
    //創(chuàng)建OSSClient實例
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    List<String> fileIds = new ArrayList<>();
    try {
      for (MultipartFile file : files) {
            //創(chuàng)建一個唯一的文件名,類似于id,就是保存在OSS服務(wù)器上文件的文件名(自定義文件名)
        String fileName = FileIdUtils.creater(fileTypeEnum.getCode());
        InputStream inputStream = file.getInputStream();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //設(shè)置數(shù)據(jù)流里有多少個字節(jié)可以讀取
        objectMetadata.setContentLength(inputStream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        fileName = StringUtils.isNotBlank(storagePath) ? storagePath + "/" + fileName : fileName;
        //上傳文件
        PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
        logger.info("Aliyun OSS AliyunOSSUtil.uploadFileToAliyunOSS,result:{}", result);
        fileIds.add(prefix + fileName);
      }
    } catch (IOException e) {
      logger.error("Aliyun OSS AliyunOSSUtil.uploadFileToAliyunOSS fail,reason:{}", e);
    } finally {
      ossClient.shutdown();
    }
    return fileIds;
  }
 
  /**
   * 刪除文件
   *
   * @param fileName
   * @param bucketName
   */
  public void deleteFile(String fileName, String bucketName) {
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    ossClient.deleteObject(bucketName, fileName);
    shutdown(ossClient);
  }
 
  /**
   * 根據(jù)圖片全路徑刪除就圖片
   *
   * @param imgUrl   圖片全路徑
   * @param bucketName 存儲路徑
   */
  public void delImg(String imgUrl, String bucketName) {
    if (StringUtils.isBlank(imgUrl)) {
      return;
    }
    //問號
    int index = imgUrl.indexOf('?');
    if (index != -1) {
      imgUrl = imgUrl.substring(0, index);
    }
    int slashIndex = imgUrl.lastIndexOf('/');
    String fileId = imgUrl.substring(slashIndex + 1);
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    ossClient.deleteObject(bucketName, fileId);
    shutdown(ossClient);
  }
 
  /**
   * 判斷文件是否存在
   *
   * @param fileName  文件名稱
   * @param bucketName 文件儲存空間名稱
   * @return true:存在,false:不存在
   */
  public boolean doesObjectExist(String fileName, String bucketName) {
    Validate.notEmpty(fileName, "fileName can be not empty");
    Validate.notEmpty(bucketName, "bucketName can be not empty");
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    try {
      boolean found = ossClient.doesObjectExist(bucketName, fileName);
      return found;
    } finally {
      shutdown(ossClient);
    }
 
  }
 
  /**
   * 復(fù)制文件
   *
   * @param fileName       源文件名稱
   * @param bucketName      源儲存空間名稱
   * @param destinationBucketName 目標(biāo)儲存空間名稱
   * @param destinationObjectName 目標(biāo)文件名稱
   */
  public void ossCopyObject(String fileName, String bucketName, String destinationBucketName, String destinationObjectName) {
    Validate.notEmpty(fileName, "fileName can be not empty");
    Validate.notEmpty(bucketName, "bucketName can be not empty");
    Validate.notEmpty(destinationBucketName, "destinationBucketName can be not empty");
    Validate.notEmpty(destinationObjectName, "destinationObjectName can be not empty");
    OSSClient ossClient = new OSSClient(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getAccessKeyId(), aliyunOSSProperties.getAccessKeySecret());
    // 拷貝文件。
    try {
      ossClient.copyObject(bucketName, fileName, destinationBucketName, destinationObjectName);
    } catch (OSSException oe) {
      logger.error("errorCode:{},Message:{},requestID:{}", oe.getErrorCode(), oe.getMessage(), oe.getRequestId());
      if (oe.getErrorCode().equals(NO_SUCH_KEY)) {
        throw new BusinessException(BusinessErrorCode.NO_SUCH_KEY);
      } else if (oe.getErrorCode().equals(NO_SUCH_BUCKET)) {
        throw new BusinessException(BusinessErrorCode.NO_SUCH_BUCKET);
      } else {
        throw new BusinessException(BusinessErrorCode.FAIL);
      }
    } finally {
      shutdown(ossClient);
    }
  }
 
  /**
   * 關(guān)閉oos
   *
   * @param ossClient ossClient
   */
  private void shutdown(OSSClient ossClient) {
    ossClient.shutdown();
  }
}

文件類型枚舉

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.file.config;
 
public enum FileTypeEnum {
 
  IMG(1, "圖片"),
  AUDIO(2, "音頻"),
  VIDEO(3, "視頻"),
  APP(4, "App包"),
  OTHER(5, "其他");
 
  private Integer code;
  private String message;
 
  FileTypeEnum(Integer code, String message) {
    this.code = code;
    this.message = message;
  }
 
  public Integer getCode() {
    return code;
  }
 
  public String getMessage() {
    return message;
  }
 
}

調(diào)用工具類上傳文件

?
1
2
3
4
5
6
7
8
9
10
11
12
@Override
  public List<String> uploadImg(MultipartFile[] files) {
    if (files == null) {
      throw new BusinessException(BusinessErrorCode.OPT_UPLOAD_FILE);
    }
    try {
      return aliyunOSSUtil.uploadFile(files, FileTypeEnum.IMG, aliyunOSSProperties.getBucketProduct(), null, aliyunOSSProperties.getDomainProduct());
    } catch (Exception e) {
      logger.error("uploadImg error e:{}", e);
      throw new BusinessException(BusinessErrorCode.UPLOAD_FAIL);
    }
  }

返回的List是文件上傳之后文件的文件名集合。
到此就整合完成了。可以登錄OSS控制臺查看對應(yīng)的文件。更多相關(guān)SpringBoot整合阿里云OSS內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://blog.csdn.net/Axela30W/article/details/96107452

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产99久久精品 | 成人区精品一区二区毛片不卡 | 亚洲国产一区二区三区a毛片 | 久久精品熟女亚洲AV国产 | 亚洲欧美日韩国产一区二区精品 | 美女福利视频一区二区 | 精品一区二区三区免费站 | 亚洲 欧美 国产 在线 日韩 | 99这里精品| 亚洲欧美日韩综合在线 | 国产在线视频第一页 | 无遮挡免费h肉动漫在线观看 | 亚洲精品成人在线 | 女海盗斯蒂内塔的复仇2免费观看 | 韩国三级动漫 | 日韩在线一区二区三区免费视频 | 国产免费午夜 | japonensis中国东北老人 | 久久综合中文字幕佐佐木希 | 国产成人亚洲精品91专区手机 | 日本一区二区三区四区无限 | 亚洲精品乱码久久久久久蜜桃欧美 | 亚洲免费视频在线 | 色v在线| 2018久久精品热在线观看 | 国产成人青草视频 | 九九九九在线精品免费视频 | 亚洲 欧美 国产 综合首页 | 精品国产免费久久久久久 | 美女用手扒开粉嫩的屁股 | 成人伊人青草久久综合网破解版 | 欧美18~20性hd| 色综合综合色 | 边吃胸边膜下刺激免费男对女 | 亚洲精品一区二区三区在线播放 | www视频在线免费观看 | 免费高清资源黄网站在线观看 | 国产剧情一区 | 91在线老王精品免费播放 | 国产成人高清精品免费观看 | 国产成人综合一区精品 |