Skip to content

Commit 6fd82d6

Browse files
committed
SpringBoot 整合 阿里云OSS 存储服务
SpringBoot 整合 阿里云OSS 存储服务,快来免费搭建一个自己的图床
1 parent fd77210 commit 6fd82d6

File tree

15 files changed

+10664
-148
lines changed

15 files changed

+10664
-148
lines changed

springboot-oss/pom.xml

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
<groupId>org.springframework.boot</groupId>
3030
<artifactId>spring-boot-starter-web</artifactId>
3131
</dependency>
32-
3332
<dependency>
3433
<groupId>org.springframework.boot</groupId>
3534
<artifactId>spring-boot-starter-test</artifactId>
@@ -40,12 +39,6 @@
4039
<groupId>org.springframework.boot</groupId>
4140
<artifactId>spring-boot-starter-thymeleaf</artifactId>
4241
</dependency>
43-
<!-- 热部署-->
44-
<dependency>
45-
<groupId>org.springframework.boot</groupId>
46-
<artifactId>spring-boot-devtools</artifactId>
47-
<optional>true</optional>
48-
</dependency>
4942
<!-- 阿里云OSS-->
5043
<dependency>
5144
<groupId>com.aliyun.oss</groupId>
@@ -57,12 +50,6 @@
5750
<artifactId>commons-fileupload</artifactId>
5851
<version>1.3.1</version>
5952
</dependency>
60-
<!-- lombok-->
61-
<dependency>
62-
<groupId>org.projectlombok</groupId>
63-
<artifactId>lombok</artifactId>
64-
<version>1.16.18</version>
65-
</dependency>
6653
<dependency>
6754
<groupId>org.springframework.boot</groupId>
6855
<artifactId>spring-boot-configuration-processor</artifactId>
26.7 KB
Loading
933 KB
Loading

springboot-oss/readme

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,6 @@
22
其他类似博客:https://blog.csdn.net/wonder_dog/article/details/81152307
33

44
遇到的问题:AliyunOSSConfig类 无法注入到 AliyunOSSConfig类中,
5-
解决办法:在Controller类中注入,然后当做参数传递到上传文件的方法中
5+
解决办法:在Controller类中注入,然后当做参数传递到上传文件的方法中
6+
7+
利用HTML5上传文件并显示在前端预览,以图片为例:https://blog.csdn.net/zhaoxiang66/article/details/79097250
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package top.snailclimb.common.constants;
2+
3+
/**
4+
* @Author: SnailClimb
5+
* @Date: 2018/12/4 15:09
6+
* @Description: 阿里云OSS存储的相关常量配置.我这里通过常量类来配置的,当然你也可以通过.properties 配置文件来配置,
7+
* 然后利用 SpringBoot 的@ConfigurationProperties 注解来注入
8+
*/
9+
public class AliyunOSSConfigConstant {
10+
//私有构造方法 禁止该类初始化
11+
private AliyunOSSConfigConstant() {
12+
}
13+
14+
//仓库名称
15+
public static final String BUCKE_NAME = "my-blog-to-use";
16+
//地域节点
17+
public static final String END_POINT = "oss-cn-beijing.aliyuncs.com";
18+
//AccessKey ID
19+
public static final String AccessKey_ID = "你的AccessKeyID";
20+
//Access Key Secret
21+
public static final String AccessKey_Secret = "你的AccessKeyIDAccessKey_Secret";
22+
//仓库中的某个文件夹
23+
public static final String FILE_HOST = "test";
24+
}
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
package top.snailclimb.common.utils;
2+
3+
4+
import com.aliyun.oss.ClientException;
5+
import com.aliyun.oss.OSSClient;
6+
import com.aliyun.oss.OSSException;
7+
import com.aliyun.oss.model.*;
8+
import org.slf4j.LoggerFactory;
9+
import org.springframework.boot.context.properties.EnableConfigurationProperties;
10+
import org.springframework.stereotype.Component;
11+
import top.snailclimb.common.constants.AliyunOSSConfigConstant;
12+
import top.snailclimb.config.AliyunOSSConfig;
13+
14+
import javax.imageio.ImageIO;
15+
import java.awt.*;
16+
import java.io.File;
17+
import java.io.IOException;
18+
import java.text.SimpleDateFormat;
19+
import java.util.Date;
20+
import java.util.UUID;
21+
22+
/**
23+
* @Author: SnailClimb
24+
* @Date: 2018/12/1 16:56
25+
* @Description: 阿里云OSS服务相关工具类.
26+
* Java API文档地址:https://help.aliyun.com/document_detail/32008.html?spm=a2c4g.11186623.6.703.238374b4PsMzWf
27+
*/
28+
@Component
29+
public class AliyunOSSUtil {
30+
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
31+
private static String FILE_URL;
32+
private static String bucketName = AliyunOSSConfigConstant.BUCKE_NAME;
33+
private static String endpoint = AliyunOSSConfigConstant.END_POINT;
34+
private static String accessKeyId = AliyunOSSConfigConstant.AccessKey_ID;
35+
private static String accessKeySecret = AliyunOSSConfigConstant.AccessKey_Secret;
36+
private static String fileHost = AliyunOSSConfigConstant.FILE_HOST;
37+
38+
39+
/**
40+
* 上传文件。
41+
*
42+
* @param file 需要上传的文件路径
43+
* @return 如果上传的文件是图片的话,会返回图片的"URL",如果非图片的话会返回"非图片,不可预览。文件路径为:+文件路径"
44+
*/
45+
public static String upLoad(File file) {
46+
// 默认值为:true
47+
boolean isImage = true;
48+
// 判断所要上传的图片是否是图片,图片可以预览,其他文件不提供通过URL预览
49+
try {
50+
Image image = ImageIO.read(file);
51+
isImage = image == null ? false : true;
52+
} catch (IOException e) {
53+
e.printStackTrace();
54+
}
55+
56+
logger.info("------OSS文件上传开始--------" + file.getName());
57+
58+
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
59+
String dateStr = format.format(new Date());
60+
61+
// 判断文件
62+
if (file == null) {
63+
return null;
64+
}
65+
// 创建OSSClient实例。
66+
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
67+
try {
68+
// 判断容器是否存在,不存在就创建
69+
if (!ossClient.doesBucketExist(bucketName)) {
70+
ossClient.createBucket(bucketName);
71+
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
72+
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
73+
ossClient.createBucket(createBucketRequest);
74+
}
75+
// 设置文件路径和名称
76+
String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
77+
if (isImage) {//如果是图片,则图片的URL为:....
78+
FILE_URL = "https://" + bucketName + "." + endpoint + "/" + fileUrl;
79+
} else {
80+
FILE_URL = "非图片,不可预览。文件路径为:" + fileUrl;
81+
}
82+
83+
// 上传文件
84+
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
85+
// 设置权限(公开读)
86+
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
87+
if (result != null) {
88+
logger.info("------OSS文件上传成功------" + fileUrl);
89+
}
90+
} catch (OSSException oe) {
91+
logger.error(oe.getMessage());
92+
} catch (ClientException ce) {
93+
logger.error(ce.getErrorMessage());
94+
} finally {
95+
if (ossClient != null) {
96+
ossClient.shutdown();
97+
}
98+
}
99+
return FILE_URL;
100+
}
101+
102+
103+
/**
104+
* 通过文件名下载文件
105+
*
106+
* @param objectName 要下载的文件名
107+
* @param localFileName 本地要创建的文件名
108+
*/
109+
public static void downloadFile(String objectName, String localFileName) {
110+
111+
// 创建OSSClient实例。
112+
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
113+
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
114+
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName));
115+
// 关闭OSSClient。
116+
ossClient.shutdown();
117+
}
118+
119+
/**
120+
* 列举 test 文件下所有的文件
121+
*/
122+
public static void listFile() {
123+
// 创建OSSClient实例。
124+
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
125+
// 构造ListObjectsRequest请求。
126+
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
127+
128+
// 设置prefix参数来获取fun目录下的所有文件。
129+
listObjectsRequest.setPrefix("test/");
130+
// 列出文件。
131+
ObjectListing listing = ossClient.listObjects(listObjectsRequest);
132+
// 遍历所有文件。
133+
System.out.println("Objects:");
134+
for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
135+
System.out.println(objectSummary.getKey());
136+
}
137+
// 遍历所有commonPrefix。
138+
System.out.println("CommonPrefixes:");
139+
for (String commonPrefix : listing.getCommonPrefixes()) {
140+
System.out.println(commonPrefix);
141+
}
142+
// 关闭OSSClient。
143+
ossClient.shutdown();
144+
}
145+
}
146+
Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
package top.snailclimb.config;
22

3-
import lombok.Getter;
4-
import lombok.Setter;
5-
import lombok.ToString;
63
import org.springframework.boot.context.properties.ConfigurationProperties;
74
import org.springframework.context.annotation.PropertySource;
85
import org.springframework.stereotype.Component;
96

10-
@Getter
11-
@Setter
12-
@ToString
7+
138
@Component
149
@PropertySource(value = "classpath:application-oss.properties")
1510
@ConfigurationProperties(prefix = "aliyun.oss")
@@ -22,4 +17,44 @@ public class AliyunOSSConfig {
2217
private String keyid;
2318
private String keysecret;
2419
private String filehost;
20+
21+
public String getBucketname() {
22+
return bucketname;
23+
}
24+
25+
public void setBucketname(String bucketname) {
26+
this.bucketname = bucketname;
27+
}
28+
29+
public String getEndpoint() {
30+
return endpoint;
31+
}
32+
33+
public void setEndpoint(String endpoint) {
34+
this.endpoint = endpoint;
35+
}
36+
37+
public String getKeyid() {
38+
return keyid;
39+
}
40+
41+
public void setKeyid(String keyid) {
42+
this.keyid = keyid;
43+
}
44+
45+
public String getKeysecret() {
46+
return keysecret;
47+
}
48+
49+
public void setKeysecret(String keysecret) {
50+
this.keysecret = keysecret;
51+
}
52+
53+
public String getFilehost() {
54+
return filehost;
55+
}
56+
57+
public void setFilehost(String filehost) {
58+
this.filehost = filehost;
59+
}
2560
}

springboot-oss/src/main/java/top/snailclimb/controller/AliyunOSSController.java

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,56 +3,73 @@
33
import org.slf4j.LoggerFactory;
44
import org.springframework.beans.factory.annotation.Autowired;
55
import org.springframework.stereotype.Controller;
6+
import org.springframework.ui.Model;
67
import org.springframework.web.bind.annotation.RequestMapping;
78
import org.springframework.web.bind.annotation.RequestParam;
9+
import org.springframework.web.bind.annotation.ResponseBody;
810
import org.springframework.web.multipart.MultipartFile;
911
import top.snailclimb.config.AliyunOSSConfig;
10-
import top.snailclimb.util.AliyunOSSUtil;
12+
import top.snailclimb.common.utils.AliyunOSSUtil;
1113

1214
import java.io.File;
1315
import java.io.FileOutputStream;
1416

1517
/**
16-
* @Auther: SnailClimb
18+
* @Author: SnailClimb
1719
* @Date: 2018/12/2 16:56
18-
* @Description: 阿里云OSS服务相关工具类
20+
* @Description: 阿里云OSS服务Controller
1921
*/
2022
@Controller
21-
@RequestMapping("/file")
23+
@RequestMapping("/oss")
2224
public class AliyunOSSController {
2325

2426
private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
25-
private static final String TO_PATH = "upLoad";
26-
private static final String RETURN_PATH = "success";
2727
@Autowired
2828
private AliyunOSSUtil aliyunOSSUtil;
29-
@Autowired
30-
private AliyunOSSConfig aliyunOSSConfig;
3129

3230
/**
3331
* 测试上传文件到阿里云OSS存储(不支持上传文件,推荐作为图床使用)
3432
*
3533
* @return
3634
*/
37-
@RequestMapping("/test")
38-
public String hello() {
39-
File file = new File("E:/Picture");
35+
@RequestMapping("/testUpload")
36+
@ResponseBody
37+
public String testUpload() {
38+
File file = new File("E:/Picture/test.jpg");
4039
AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil();
41-
String url = aliyunOSSUtil.upLoad(file, aliyunOSSConfig);
40+
String url = aliyunOSSUtil.upLoad(file);
4241
System.out.println(url);
4342
return "success";
4443
}
4544

46-
@RequestMapping("/toUpLoadFile")
47-
public String toUpLoadFile() {
48-
return TO_PATH;
45+
/**
46+
* 通过文件名下载文件
47+
*/
48+
@RequestMapping("/testDownload")
49+
@ResponseBody
50+
public String testDownload() {
51+
AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil();
52+
aliyunOSSUtil.downloadFile(
53+
"test/2018-12-04/e3f892c27f07462a864a43b8187d4562-rawpixel-600782-unsplash.jpg","E:/Picture/e3f892c27f07462a864a43b8187d4562-rawpixel-600782-unsplash.jpg");
54+
return "success";
55+
}
56+
57+
/**
58+
* 列出某个文件夹下的所有文件
59+
*/
60+
@RequestMapping("/testListFile")
61+
@ResponseBody
62+
public String testListFile() {
63+
AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil();
64+
aliyunOSSUtil.listFile();
65+
return "success";
4966
}
5067

5168
/**
5269
* 文件上传
5370
*/
5471
@RequestMapping(value = "/uploadFile")
55-
public String uploadBlog(@RequestParam("file") MultipartFile file) {
72+
public String uploadBlog(@RequestParam("file") MultipartFile file, Model model) {
5673
logger.info("文件上传");
5774
String filename = file.getOriginalFilename();
5875
System.out.println(filename);
@@ -66,13 +83,14 @@ public String uploadBlog(@RequestParam("file") MultipartFile file) {
6683
os.close();
6784
file.transferTo(newFile);
6885
// 上传到OSS
69-
String uploadUrl = aliyunOSSUtil.upLoad(newFile, aliyunOSSConfig);
86+
String uploadUrl = aliyunOSSUtil.upLoad(newFile);
87+
model.addAttribute("url",uploadUrl);
7088
}
7189

7290
}
7391
} catch (Exception ex) {
7492
ex.printStackTrace();
7593
}
76-
return RETURN_PATH;
94+
return "success";
7795
}
7896
}

0 commit comments

Comments
 (0)