我們在進行項目開發時,經常需要進行文件、圖片等的上傳。對於很多項目來說,雖然有FastDFS等文件存儲服務器技術,但其實我們完全沒有必要搭建自己的圖片等文件服務器。對一個小型非專業的應用來說,搭建自己的專屬文件存儲服務器,完全就是浪費,而且你們公司也不一定有那樣的技術實力。
但我們項目中又經常需要進行圖片等各種文件的上傳、下載操作,那該如何實現呢?
這裡壹哥給大家推薦使用阿里雲存儲,便宜又靠譜!所以今天 壹哥 會帶大家學習如何使用阿里雲的OSS實現文件上傳。
一. 阿里雲OSS簡介
1. 存儲服務簡介
阿里雲提供了一個對象存儲 OSS服務,可以實現海量、安全、低成本、高可靠的雲存儲服務,提供99.9999999999%的數據可靠性。並且使用RESTful API 可以在互聯網任何位置存儲和訪問,容量和處理能力彈性擴展,多種存儲類型供選擇全面優化存儲成本。
2. 購買阿里雲OSS服務
首選搜索阿里雲,選擇第一個就是了。

然後選擇雲計算基礎里的對象存儲OSS產品。


可以看到,40G的一年存儲服務才9塊錢,很便宜了,對於學習來說足夠了。

3. 阿里雲OSS控制台
點擊首頁的控制台鏈接就可以進入後台。


在這裡創建一個Bucket桶,作為存儲文件的空間。

桶名不能重複。

可以在自己的桶空間中創建子目錄,用來存儲不同項目或模塊下的文件。

接下來要設置該目錄的訪問權限,可以設置為公共讀。

再設置一下該桶的授權策略。


二. SpringBoot中實現OSS雲存儲
1. 創建Web項目
我們按照之前的經驗,創建一個web程序,並將之改造成Spring Boot項目,具體過程略。

2. 添加依賴包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--簡化bean代碼-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 圖片上傳 SDK 阿里雲oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>commons-Fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>3.創建配置信息
可以在這裡查看自己阿里雲賬號的AccessKey信息。


bucketName: "yiyige"
accessKeyId: "自己阿里雲的accessKey"
accessKeySecret: "自己阿里雲的accessKey"
#OSS對應的區域
endpoint: "http://oss-cn-hangzhou.aliyuncs.com"
filehost: "images"4. 創建配置信息類
package com.yyg.boot.config;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* 把配置文件中的配置信息讀取到該類中.
*/
@Data
@Configuration
public class OssConfiguration {
@Value("${endpoint}")
private String endPoint;
@Value("${accessKeyId}")
private String accessKeyId;
@Value("${accessKeySecret}")
private String accessKeySecret;
@Value("${filehost}")
private String fileHost;
@Value("${bucketName}")
private String bucketName;
}5. 封裝阿里雲文件上傳工具類
package com.yyg.boot.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.yyg.boot.config.OssConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* 封裝文件上傳方法
*/
@Component
public class AliyunOssUtil {
@Autowired
private OssConfiguration config;
public String upload(File file) {
if (file == null) {
return null;
}
String endPoint = config.getEndPoint();
String keyId = config.getAccessKeyId();
String keySecret = config.getAccessKeySecret();
String bucketName = config.getBucketName();
String fileHost = config.getFileHost();
//定義子文件的格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
//阿里雲文件上傳客戶端
OSSClient client = new OSSClient(endPoint, keyId, keySecret);
try {
//判斷桶是否存在
if (!client.doesBucketExist(bucketName)) {
//創建桶
client.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
//設置訪問權限為公共讀
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
//發起創建桶的請求
client.createBucket(createBucketRequest);
}
//當桶存在時,進行文件上傳
//設置文件路徑和名稱
String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
//文件上傳成功後,返回當前文件的路徑
if (result != null) {
return fileUrl;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client.shutdown();
}
}
return null;
}
}6. 編寫Controller接口
package com.yyg.boot.web;
import com.yyg.boot.util.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
@Controller
public class OssController {
@Autowired
private AliyunOssUtil ossUtil;
@GetMapping("/")
public String showUploadFile() {
return "upLoad";
}
@PostMapping("/uploadFile")
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file != null) {
String fileName = file.getOriginalFilename();
if (!"".equals(fileName.trim())) {
File newFile = new File(fileName);
FileOutputStream os = new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
//把file里的內容複製到奧newFile中
file.transferTo(newFile);
String upload = ossUtil.upload(newFile);
//圖片回顯地址:
//http://yiyige.oss-cn-hangzhou.aliyuncs.com/images/2019-10-21/6c964702b67d4eeb920e7f1f4358189b-dishu.jpg
System.out.println("path=" + upload);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
}7. 編寫文件上傳頁面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8"/>
<title>【基於OSS的上傳文件頁面】</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" media="all"/>
<style type="text/css">
*{
margin:0;
padding:0;
}
#group{
position: absolute;
left:580px;
}
#submit{
position: absolute;
top:140px;
left:580px;
}
</style>
</head>
<body>
<div align="center">
<h2 style="color:orangered;">基於OSS的上傳文件頁面</h2>
</div>
<br/>
<form action="/uploadFile" enctype="multipart/form-data" method="post">
<div class="form-group" id="group">
<label for="exampleInputFile">File input</label>
<input type="file" id="exampleInputFile" name="file"/>
</div>
<button type="submit" class="btn btn-default" id="submit">上傳</button>
</form>
</body>
</html>8. 文件上傳成功界面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8"/>
<title>【文件上傳成功頁面】</title>
</head>
<body>
<div align="center">
<h5>上傳成功</h5>
</div>
</body>
</html>9. 編寫入口類
package com.yyg.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}10. 進行測試
首先進入到文件上傳界面,選擇一個文件進行上傳。

上傳成功。

打開控制台,可以看到阿里雲OSS服務器端返回的圖片路徑。

然後我們去阿里雲服務器上可以看到自動以當天日期創建了一個文件夾,這裡存放的就是當天上傳的文件。

在這個文件夾里看到剛才上傳的圖片文件。

結語
至此,壹哥 就把阿里雲OSS的使用教程給大家介紹完了,現在你學會了嗎?最後壹哥可以偷偷告訴你一個小秘訣,你完全可以利用阿里雲OSS搭建一個自己的私密「雲盤」哦,至於裏面存什麼內容,自己悟吧!
作者:一一哥Sun
鏈接:https://juejin.cn/post/7178627128269733949
來源:稀土掘金