服务器之家

服务器之家 > 正文

springboot整合阿里云oss上传的方法示例

时间:2020-08-10 15:52     来源/作者:╱/.独﹄無㈡oоΟ

 

OSS申请和配置

 

1. 注册登录

输入网址:https://www.aliyun.com/product/oss

springboot整合阿里云oss上传的方法示例

如果没有账号点击免费注册,然后登录。

2.开通以及配置

点击立即开通

springboot整合阿里云oss上传的方法示例

进入管理控制台

springboot整合阿里云oss上传的方法示例

第一次使用会出现引导,按引导点击“我知道了”,然后点击创建Bucket。

springboot整合阿里云oss上传的方法示例

springboot整合阿里云oss上传的方法示例

如果没有存储包或流量包点击购买。

springboot整合阿里云oss上传的方法示例

点击确定,返回主页面,出现该页面,点击我知道了

springboot整合阿里云oss上传的方法示例

将EndPoint记录下来,方便后期添加到我们项目的配置文件中

springboot整合阿里云oss上传的方法示例

创建 AccessKeyID 和 AccessKeySecret

springboot整合阿里云oss上传的方法示例

点击创建Access key,第一次需要短信验证,验证成功后弹出

保留Access key 以及 AccessKeySecret 信息

 

springboot整合使用

1. 进入我们springboot的项目中,导入oss相关依赖

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

2. 再配置文件中添加相关信息

springboot整合阿里云oss上传的方法示例

?
1
2
3
4
5
6
7
oss.aliyun.accessKeyId= #
oss.aliyun.accessKeySecret= #
oss.aliyun.bucketName= mutest-qcby-oss
oss.aliyun.endpoint= #
oss.aliyun.pubFlag= false
oss.aliyun.expiration= 100
oss.aliyun.sslNmae= #内网使用,不必须

3. 书写获取配置信息的java文件,建立properties包(导入依赖,否则无法识别这个包)

?
1
2
3
4
5
<dependency>
     <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
 </dependency>

springboot整合阿里云oss上传的方法示例

OssProerties.java

?
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
import com.mbyte.easy.oss.OssUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
 
/**
 * @ClassName: OssProerties
 * @Description: 阿里云 对象云存储配置类
 * @Author: zte
 * @Date: 2019-02-14 09:37
 * @Version 1.0
 **/
@Data
@Component
@ConfigurationProperties(prefix = "oss.aliyun")
public class OssProerties {
 private String accessKeyId;
 private String accessKeySecret;
 private String bucketName;
 private String endpoint;
 private String bucket;
 private boolean pubFlag;
 private String sslNmae;
 
 @PostConstruct
 public void init(){
  //Oss工具类配置初始化
  OssUtil.initConfig(this);
 }
 
 
 //过期时间
 private int expiration;
 
 public String getAccessKeyId() {
  return accessKeyId;
 }
 
 public OssProerties setAccessKeyId(String accessKeyId) {
  this.accessKeyId = accessKeyId;
  return this;
 }
 
 public String getAccessKeySecret() {
  return accessKeySecret;
 }
 
 public OssProerties setAccessKeySecret(String accessKeySecret) {
  this.accessKeySecret = accessKeySecret;
  return this;
 }
 
 public String getBucketName() {
  return bucketName;
 }
 
 public OssProerties setBucketName(String bucketName) {
  this.bucketName = bucketName;
  return this;
 }
 
 public String getEndpoint() {
  return endpoint;
 }
 
 public OssProerties setEndpoint(String endpoint) {
  this.endpoint = endpoint;
  return this;
 }
 
 public String getBucket() {
  return bucket;
 }
 
 public OssProerties setBucket(String bucket) {
  this.bucket = bucket;
  return this;
 }
 
 public boolean isPubFlag() {
  return pubFlag;
 }
 
 public void setPubFlag(boolean pubFlag) {
  this.pubFlag = pubFlag;
 }
 
 public int getExpiration() {
  return expiration;
 }
 
 public OssProerties setExpiration(int expiration) {
  this.expiration = expiration;
  return this;
 }
 
 @Override
 public String toString() {
  return "OssPro{" +
    "accessKeyId='" + accessKeyId + '\'' +
    ", accessKeySecret='" + accessKeySecret + '\'' +
    ", bucketName='" + bucketName + '\'' +
    ", endpoint='" + endpoint + '\'' +
    ", bucket='" + bucket + '\'' +
    ", expiration=" + expiration +
    '}';
 }
}

4. 整合oss,书写相关java文件

1. 文件常量java文件 FileConstants.java

?
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
package com.mbyte.easy.oss;
 
import org.springframework.util.ClassUtils;
 
import java.io.File;
 
/**
 * @ClassName: FileConstants
 * @Description: 文件常量
 * @Author: lxt
 * @Date: 2019-02-19 09:59
 * @Version 1.0
 **/
public class FileConstants {
 /**
  * 文件存储临时文件夹
  */
 public final static String TEMP_ROOT = "temp";
 /**
  * 下载暂存目录
  */
 public final static String DOWNLOAD = TEMP_ROOT+ File.separator+"download";
 /**
  * 后缀名相关常量(包含【.】)
  */
 public final static String SUFFIX_ZIP = ".zip";
 /**
  * png图片后缀
  */
 public final static String SUFFIX_png = ".png";
 /**
  * 二维码暂存路径 eg:微信支付二维码
  */
 public static final String QRCODE = "qrcode";
 public static final String QRCODE_PATH = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+File.separator+QRCODE;
 
 /**
  * 文件的后缀名
  */
 public static final String FILE_TYPE_AVI = "avi";
 public static final String FILE_TYPE_CSV = "csv";
 public static final String FILE_TYPE_DOC = "doc";
 public static final String FILE_TYPE_DOCX = "docx";
 public static final String FILE_TYPE_MP3 = "mp3";
 public static final String FILE_TYPE_PDF = "pdf";
 public static final String FILE_TYPE_PPT = "ppt";
 public static final String FILE_TYPE_PPTX = "pptx";
 public static final String FILE_TYPE_RAR = "rar";
 public static final String FILE_TYPE_TXT = "txt";
 public static final String FILE_TYPE_XLS = "xls";
 public static final String FILE_TYPE_ZIP = "zip";
 /**
  * 文件对应图片的oss路径
  */
 public static final String FILE_TYPE_AVI_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092751242.U27AJS.png?Expires=4731182871&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=0S4nIClHiI11Iw2SOnLoKuwpiDc%3D";
 public static final String FILE_TYPE_CSV_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092859378.A0J8R6.png?Expires=4731182939&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=McS77A%2BMOkmSjBfZziIxLeR5QCM%3D";
 public static final String FILE_TYPE_DOC_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092908602.QHFWCO.png?Expires=4731182949&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=%2Fr9V%2FP8nmfYKVbANe2fl1qR%2FFwg%3D";
 public static final String FILE_TYPE_DOCX_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092908602.QHFWCO.png?Expires=4731182949&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=%2Fr9V%2FP8nmfYKVbANe2fl1qR%2FFwg%3D";
 public static final String FILE_TYPE_MP3_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092920411.L5CBAF.png?Expires=4731182960&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=wPz2ylPAg%2FpBqyIz4LztacVfRwo%3D";
 public static final String FILE_TYPE_PDF_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092930146.CU0CAD.png?Expires=4731182970&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=Nwl6%2BkZmosARipe%2BoVJT3FdRLqM%3D";
 public static final String FILE_TYPE_PPT_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092939365.XHOX9G.png?Expires=4731182979&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=3CDxl0W5ymVXe2XLnxLn1ewc1gU%3D";
 public static final String FILE_TYPE_PPTX_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092939365.XHOX9G.png?Expires=4731182979&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=3CDxl0W5ymVXe2XLnxLn1ewc1gU%3D";
 public static final String FILE_TYPE_RAR_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092949684.9OW7L9.png?Expires=4731182989&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=RCKarsekmPG3CXI5D6MLpJ4ocj4%3D";
 public static final String FILE_TYPE_TXT_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092959887.TF1K0N.png?Expires=4731183000&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=9l44IQ0FZdQMcRq92PPOXlBKEFk%3D";
 public static final String FILE_TYPE_XLS_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205093007830.M6O08Z.png?Expires=4731183008&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=GeNmvgi7TGMq3uk9AG0%2BJRWRFY0%3D";
 public static final String FILE_TYPE_ZIP_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205093017998.Q39L45.png?Expires=4731183018&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=djzJ7rTgH8LvCeaMfWGXUAQIpJE%3D";
}

2. 文件操作工具类 OssFileUtils.java

?
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.oss.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
 
/**
 * @ClassName: DesignFileUtils
 * @Description: 文件操作工具类
 * @Author: lxt
 * @Date: 2019-02-15 14:50
 * @Version 1.0
 **/
@Slf4j
public class OssFileUtils {
 /**
  * @Title: uploadSingleFile
  * @Description: 单个文件上传
  * @Author: zte
  * @param: file
  * @Date: 2019-02-15 14:56
  * @return: java.lang.String 成功返回 文件路径,失败返回null
  * @throws:
  */
 public static String uploadSingleFile(MultipartFile file){
  if(file == null){
   log.error("单文件上传失败,文件为空");
   return null;
  }
  try {
   return OssUtil.upload(OssUtil.generateKey(file.getOriginalFilename()),file.getBytes());
  } catch (Exception e) {
   log.error("单文件上传异常【"+file+"】",e);
  }
  return null;
 }
 /**
  * @Title: uploadSingleFile
  * @Description: 单个文件上传
  * @Author: lxt
  * @param: file
  * @Date: 2019-02-15 14:56
  * @return: java.lang.String 成功返回 文件路径,失败返回null
  * @throws:
  */
 public static String uploadSingleFile(File file){
  if(file == null){
   log.error("单文件上传失败,文件为空");
   return null;
  }
  try {
   return OssUtil.upload(OssUtil.generateKey(file.getName()),file);
  } catch (Exception e) {
   log.error("单文件上传异常【"+file+"】",e);
  }
  return null;
 }
 /**
  * @Title: uploadMultipartFile
  * @Description: 多文件文件上传
  * @Author: zte
  * @param: files
  * @Date: 2019-02-18 13:08
  * @return: java.util.List<java.lang.String> 成功返回 文件路径集合,失败返回null
  * @throws:
  */
 public static List<String> uploadMultipartFile(List<MultipartFile> fileList){
  List<String> filePaths = new ArrayList<>();
  Optional.ofNullable(fileList).ifPresent(fl->{
      fl.stream().forEach(f->{
       try {
        filePaths.add(OssUtil.upload(OssUtil.generateKey(f.getOriginalFilename()),f.getBytes()));
       } catch (IOException e) {
        log.error("多文件上传异常【"+f+"】",e);
       }
      });
    }
  );
  return filePaths;
 }
 /**
  * @Title: downloadSingleFileByOss
  * @Description: 下载阿里云文件到本地
  * @Author: lxt
  * @param: url 阿里云链接
  * @param: filePath 下载目录
  * @Date: 2019-02-18 13:13
  * @return: java.io.File
  * @throws:
  */
 public static File downloadSingleFile(String url,String filePath){
  try {
   return OssUtil.download2File(url,filePath);
  } catch (Exception e) {
   log.error("单文件下载异常【"+url+"】",e);
  }
  return null;
 }
 /**
  * @Title: downloadMultipartFileByOss
  * @Description: 批量下载阿里云文件到本地
  * @Author: zte
  * @param: urlList 阿里云链接集合
  * @param: dir 下载目录
  * @Date: 2019-02-18 13:19
  * @return: java.util.List<java.io.File>
  * @throws:
  */
 public static List<File> downloadMultipartFile(List<String> urlList,String dir){
  List<File> files = new ArrayList<>();
  Optional.ofNullable(urlList).ifPresent(fl->{
     fl.stream().forEach(f->files.add(OssUtil.download2Dir(f,dir)));
    }
  );
  return files;
 }
 /**
  * @Title: downloadMultipartFileByOssWithZip
  * @Description: 批量下载,打包成一个zip包
  * @Author: zte
  * @param: urlList
  * @param: zipPath
  * @Date: 2019-02-18 15:41
  * @return: java.io.File
  * @throws:
  */
// public static File downloadMultipartFileWithZip(List<String> urlList,String zipName){
//  try {
//   //压缩路径不存在,先创建
//   File zipDirFile = new File(FileConstants.DOWNLOAD);
//   if(!zipDirFile.exists()){
//    zipDirFile.mkdirs();
//   }
//   if(StringUtils.isNoneBlank(zipName) && !isFileBySuffix(zipName,FileConstants.SUFFIX_ZIP)){
//    //文件名称存在 但后缀名不是zip
//    zipName = zipName + FileConstants.SUFFIX_ZIP;
//   }else{
//    // 压缩包默认名称未6为随机字符串
//    zipName = StringUtils.isBlank(zipName) ? Utility.getRandomStrByNum(6)+FileConstants.SUFFIX_ZIP : zipName;
//   }
//   // 批量下载文件到指定位置
//   List<File> files = downloadMultipartFile(urlList,FileConstants.DOWNLOAD);
//   // 将文件打包
//   File zipFile = ZipFileUtil.compressFiles2Zip(files,FileConstants.DOWNLOAD+File.separator+zipName);
//   // 删除打包之前的文件
//   files.stream().forEach(f->f.delete());
//   return zipFile;
//  }catch (Exception e){
//   logger.error("批量下载文件异常",e);
//  }
//  return null;
// }
 
 /**
  * @Title: isFileBySuffix
  * @Description: 通过后缀名判断是否是某种文件
  * @Author: zte
  * @param: fileName 文件名称
  * @param: suffix 后缀名
  * @Date: 2019-02-19 10:09
  * @return: boolean
  * @throws:
  */
 public static boolean isFileBySuffix(String fileName,String suffix){
  if(StringUtils.isNoneBlank(fileName) && StringUtils.isNoneBlank(suffix)){
   return fileName.endsWith(suffix.toLowerCase()) || fileName.endsWith(suffix.toUpperCase());
  }
  return false;
 }
 /**
  * @Title: downloadByUrlPath
  * @Description: 下载网络文件
  * @Author: lxt
  * @param: urlPath
  * @param: saveDir
  * @param: fileName
  * @Date: 2019-02-23 16:26
  * @return: java.io.File
  * @throws:
  */
 public static File downloadByUrlPath(String urlPath,String saveDir,String fileName){
  if(StringUtils.isBlank(urlPath)){
   log.error("下载网络文件失败,链接为空");
   return null;
  }
  try (InputStream ins = new URL(urlPath).openStream()) {
   Path target = Paths.get(saveDir, fileName);
   Files.createDirectories(target.getParent());
   Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
   return new File(saveDir+File.separator+fileName);
  } catch (IOException e) {
   log.error("下载网络文件异常",e);
  }
  return null;
 }
// /**
//  * @Description: 上传视频文件
//  * @param file
//  * @param type
//  * @return: com.mbyte.easy.common.web.AjaxResult
//  * @Author: zte
//  * @Date: 2020/3/23 17:48
//  */
// public static AjaxResult uploadVideoFile(MultipartFile file,String type){
//  if(file!=null){
//   File partFile = null;
//   File compressFile = null;
//   try {
//    Map<String,String> result = new HashMap<>();
//    // 压缩视频
//    if(VideoDetailConstants.VIDEO_W_FLAG.equals(type)){
//     compressFile = FfmpegUtil.INSTANCE.compressFile2W(file);
//    }
//    if(VideoDetailConstants.VIDEO_H_FLAG.equals(type)){
//     compressFile = FfmpegUtil.INSTANCE.compressFile2H(file);
//    }
//    String fileUrlPath = null;
//    if(compressFile != null){
//     fileUrlPath = OssFileUtils.uploadSingleFile(compressFile);
//     // 剪辑视频
//     partFile = FfmpegUtil.INSTANCE.getPartVideo(compressFile);
//    }else{
//     fileUrlPath = OssFileUtils.uploadSingleFile(file);
//     // 剪辑视频
//     partFile = FfmpegUtil.INSTANCE.getPartVideo(file);
//    }
//    // 上传视频本身到oss
//    result.put("video",fileUrlPath);
//    // 上传试看部分到oss
//    result.put("videoPart", OssFileUtils.uploadSingleFile(partFile));
//    return AjaxResult.success(result);
//   }catch (Exception e){
//    log.error("上传视频异常",e);
//   }finally {
//    if(partFile != null && partFile.exists()){
//     partFile.delete();
//    }
//    if(compressFile != null && compressFile.exists()){
//     compressFile.delete();
//    }
//   }
//  }
//  return AjaxResult.error();
// }
}

3. 阿里云 对象云存储工具类 OssUtil.java

?
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.mbyte.easy.properties.OssProerties;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @ClassName: OSSUtill
 * @Description: 阿里云 对象云存储工具类
 * @Author: zte
 * @Date: 2019-02-13 14:38
 * @Version 1.0
 **/
@Slf4j
public class OssUtil {
 /**
  * 注入配置
  */
 private static OssProerties ossProerties;
 /**
  * @Title: initConfig
  * @Description: 配置初始化
  * @Author: lxt
  * @param: ossProertiesInit
  * @Date: 2019-02-14 09:25
  * @throws:
  */
 public static void initConfig(OssProerties ossProertiesInit){
  ossProerties = ossProertiesInit;
 }
 
 /**
  * @Title: generateKey
  * @Description: 生成oss对象名称
  * @Author: lxt
  * @param: fileName
  * @Date: 2019-02-13 15:21
  * @return: java.lang.String
  * @throws:
  */
 public static String generateKey(String fileName) {
  //对象名称格式:yyyymm.name.6位随机字符.ext
  return new StringBuilder(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"))
    .append(".").append(Utility.getRandomStrByNum(6))
    .append(".").append(FilenameUtils.getExtension(fileName))
    .toString();
 }
 
 public static String getHttpsAddress(String url){
  return url.replaceAll("http://"+ossProerties.getBucket(),ossProerties.getSslNmae());
 }
 
 /**
  * @Title: upload
  * @Description: 上传方法
  * @Author: zte
  * @param: key 对象名称
  * @param: file待上传文件
  * @Date: 2019-02-13 15:35
  * @return: java.lang.String
  * @throws:
  */
 public static String upload(String key,File file) {
  if(file == null || !file.exists()){
   log.error("阿里云上传文件失败【"+file+"】不存在");
   return null;
  }
  log.info("阿里云上传文件开始:【"+file+"】");
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   ossClient.putObject(ossProerties.getBucketName(),key,file);
   //设置url过期时间
   Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration());
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上传文件结束:【"+file+"】=>【"+url+"】");
   return getHttpsAddress(url);
  }catch(Exception e) {
   log.error("阿里云上传文件异常【"+file+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: upload
  * @Description: 上传方法
  * @Author: zte
  * @param: key 对象名称
  * @param: file待上传文件
  * @Date: 2019-02-13 15:35
  * @return: java.lang.String
  * @throws:
  */
 public static String upload(String key,byte[] bytes) {
  if(bytes == null || StringUtils.isBlank(key)){
   log.error("阿里云上传文件不存在:【"+key+"】");
   return null;
  }
  log.info("阿里云上传文件开始:【"+key+"】");
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   ossClient.putObject(ossProerties.getBucketName(),key, new ByteArrayInputStream(bytes));
   //设置url过期时间
   Date expirationDate = DateUtils.addYears(new Date(), 100);
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上传文件结束:【"+key+"】=>【"+url+"】");
   return getHttpsAddress(url);
  }catch(Exception e) {
   log.error("阿里云上传文件异常:【"+key+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: uploadWithObjectName
  * @Description: 上传方法,返回对象名称和 url
  * @Author: zte
  * @param: file待上传文件
  * @Date: 2019-02-13 15:35
  * @return: java.lang.Map<String,String>
  * @throws:
  */
 public static Map<String,String> uploadWithObjectName(File file) {
  if(file == null || !file.exists()){
   log.error("阿里云上传文件失败【"+file+"】不存在");
   return null;
  }
  Map<String,String> map = new HashMap<>();
  log.info("阿里云上传文件开始:【"+file+"】");
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   String key = generateKey(file.getName());
 
   ossClient.putObject(ossProerties.getBucketName(),key, new FileInputStream(file));
   //设置url过期时间
   Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration());
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上传文件结束:【"+file+"】=>【"+url+"】");
   map.put("objectName",key);
   map.put("url",url);
   return map;
  }catch(Exception e) {
   log.error("阿里云上传文件异常【"+file+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: delete
  * @Description: 删除方法
  * @Author: zte
  * @param: url 待删除对象url
  * @Date: 2019-02-13 15:54
  * @throws:
  */
 public static void delete(String url) {
  if(StringUtils.isBlank(url)){
   log.error("阿里云删除文件失败,对象url为空");
   return;
  }
  log.info("阿里云删除文件开始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根据url获取对象名称
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   // 删除文件
   ossClient.deleteObject(ossProerties.getBucketName(), url);
   log.info("阿里云删除文件结束:【"+url+"】");
  }catch(Exception e) {
   log.error("阿里云删除文件异常【"+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
 }
 /**
  * @Title: download
  * @Description: 下载文件到本地文件
  * @Author: zte
  * @param: url 待下载对象url
  * @param: filePath 下载到本地文件
  * @Date: 2019-02-13 15:56
  * @return: java.io.File
  * @throws:
  */
 public static File download2File(String url, String filePath) {
  log.info("阿里云下载文件开始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根据url获取对象名称
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   File file = new File(filePath);
   // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
   ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file);
   log.info("阿里云下载文件结束:【"+url+"】");
   return file;
  }catch(Exception e) {
   log.error("阿里云下载文件异常【"+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: download
  * @Description: 通过流下载文件
  * @Author: zte
  * @param: url 待下载对象url
  * @param: filePath 下载到本地文件
  * @Date: 2019-02-13 15:56
  * @return: java.io.File
  * @throws:
  */
 public static void download2FileByStream(String url, String fileName, HttpServletResponse response) {
  BufferedInputStream inputStream = null;
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try(
    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());){
   // 配置文件下载
   response.setHeader("content-type", "application/octet-stream");
   response.setContentType("application/octet-stream");
   if(url.contains(ossProerties.getBucket())){
    //根据url获取对象名称
    url = getObjectNameByUrl(url);
   }
   // 下载文件能正常显示中文
   response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8"));
   log.info("阿里云下载文件开始:【"+url+"】");
   // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
   OSSObject ossObject = ossClient.getObject(ossProerties.getBucketName(), url);
   inputStream = new BufferedInputStream(ossObject.getObjectContent());
   byte[] buff = new byte[2048];
   int bytesRead;
   while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))){
    outputStream.write(buff, 0, bytesRead);
   }
   outputStream.flush();
  } catch (Exception e) {
   log.error("下载异常!", e);
  }finally {
   log.info("阿里云下载文件结束:【"+url+"】");
   ossClient.shutdown();
   if(inputStream != null){
    try {
     inputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 /**
  * @Title: download
  * @Description: 下载文件到指定目录,文件名称为阿里云文件对象名称
  * @Author: zte
  * @param: url 待下载对象url
  * @param: dir 下载到本地目录
  * @Date: 2019-02-13 15:56
  * @return: java.io.File
  * @throws:
  */
 public static File download2Dir(String url, String dir) {
  log.info("阿里云下载文件开始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根据url获取对象名称
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   File file = new File(dir+File.separator+url);
   // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
   ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file);
   log.info("阿里云下载文件结束:【"+url+"】");
   return file;
  }catch(Exception e) {
   log.error("阿里云下载文件异常【"+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /*
  * @Title: getObjectNameByUrl
  * @Description: 通过url获取对象名称
  * @Author: lxt
  * @param: url
  * @Date: 2019-02-13 16:20
  * @return: java.lang.String
  * @throws:
  */
 public static String getObjectNameByUrl(String url){
  if(StringUtils.isBlank(url)){
   return null;
  }
  return url.substring(url.indexOf(ossProerties.getBucket())+ossProerties.getBucket().length()+1,url.indexOf("?"));
 }
 
 /**
  * @author: zte
  * @description: 重载方法,根据file生成文件名称并且上传文件到阿里云
  * @date: 2019/9/21 10:56
  * @param file : MultipartFile文件
  * @see #upload(String,byte[])
  * @return 数据库中要存入的路径
  */
 public static String upload(MultipartFile file) throws IOException {
  if (file == null || Strings.isEmpty(file.getOriginalFilename())){
   return null;
  }
  return upload(generateKey(file.getOriginalFilename()), file.getBytes());
 }
 
 
 /**
  * 调用浏览器下载
  * @param url
  * @param response
  */
 public static void download2FileByStream(String url,HttpServletResponse response,String name) {
 
  File file = new File(url);
  String fileName=file.getName();
  fileName= StringUtils.substringBefore(fileName,"?");
  String fileLast=StringUtils.substringAfterLast(fileName,".");
 
  fileName=name+"."+fileLast;
 
 
  BufferedInputStream inputStream = null;
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try(
 
    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());){
   // 配置文件下载
   response.setHeader("content-type", "application/octet-stream");
   response.setContentType("application/octet-stream");
   if(url.contains(ossProerties.getBucket())){
    //根据url获取对象名称
    url = getObjectNameByUrl(url);
   }
   // 下载文件能正常显示中文
   response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8"));
   log.info("阿里云下载文件开始:【"+url+"】");
   // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
   OSSObject ossObject = ossClient.getObject(ossProerties.getBucketName(), url);
   inputStream = new BufferedInputStream(ossObject.getObjectContent());
   byte[] buff = new byte[2048];
   int bytesRead;
   while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))){
    outputStream.write(buff, 0, bytesRead);
   }
   outputStream.flush();
  } catch (Exception e) {
   log.error("下载异常!", e);
  }finally {
   log.info("阿里云下载文件结束:【"+url+"】");
   ossClient.shutdown();
   if(inputStream != null){
    try {
     inputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

5. controller 调用样例

我这里使用的是我自己项目封装的 AjaxResult工具类,大家可以使用Map,通过这个方法呢,我们就可以使用oss将图片保存,并且返回前端图片的保存地址(可以访问)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
  * 上传
  * @param fileupload
  * @return
  */
 @PostMapping("uploadImg")
 @ResponseBody
 public AjaxResult uploadImg(MultipartFile fileupload){
  if(fileupload != null){
   String path = OssFileUtils.uploadSingleFile(fileupload);
   return AjaxResult.success(path);
  }else {
   return AjaxResult.error();
  }
 
 }

到此这篇关于springboot整合阿里云oss上传的方法示例的文章就介绍到这了,更多相关springboot整合阿里云oss上传内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_44922113/article/details/107891024

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
返回顶部