一、需求分析
文件上傳是一個非常常見的功能,就是通過IO流將文件寫到另外一個地方,這個地方可以是項目下的某個文件夾裏,或者是本地電腦某個盤下面,還可以是雲服務OSS裏面,這裏就是我要講到的OSS,我寫的是基於阿里雲的。
二:環境搭建
我這裏是用的Springboot.Thymeleaf插件,爲了在html頁面實現文件上傳功能。
1、首先開通阿里雲OSS存儲,這裏不多說了。
2、創建一個Bucket
這個bucket名稱是等下參數裏面要用到的。區域可以選擇你那邊的區域。
3、創建好之後返回剛纔的頁面,點擊Access Key,來獲取accessKeyId、accessKeySecret這兩個參數
4、Maven依賴(Thymeleaf、OSS)
<!-- 阿里雲OSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
5、新建一個UpLoadController.java
**
* @author 小四
* @descibe oss
* @date 2020/5/27 13:19
*/
@Controller
public class UpLoadController {
private static final String TO_PATH = "upload";
private static final String RETURN_PATH = "success";
@Autowired
private AliyunOSSUtil aliyunOSSUtil;
@RequestMapping("/toUpLoadFile")
public String toUpLoadFile() {
return TO_PATH;
}
/**
* 文件上傳
*/
@RequestMapping(value = "/uploadFile")
public String uploadBlog(@RequestParam("file") MultipartFile file) {
String filename = file.getOriginalFilename();
System.out.println(filename + "==filename");
try {
if (file != null) {
if (!"".equals(filename.trim())) {
File newFile = new File(filename);
FileOutputStream os = new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
file.transferTo(newFile);
// 上傳到OSS
String uploadUrl = aliyunOSSUtil.upLoad(newFile);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return RETURN_PATH;
}
}
6、新建AliyunOSSUtil.java
/**
* @author 小四
* @descibe oss
* @date 2020/5/27 13:18
*/
@Component
public class AliyunOSSUtil {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
/**
* 上傳文件
*/
public String upLoad(File file) {
logger.info("------OSS文件上傳開始--------" + file.getName());
String endpoint = "你的endpoint ";
//這裏endpoint 在你的bucket列表->點擊你的bucket->點擊概覽中間就有,下面有截圖
System.out.println("獲取到的Point爲:" + endpoint);
String accessKeyId = "你的accessKeyId "; //accessKeyId 、accessKeySecret 上面有說到哪裏獲取
String accessKeySecret = "你的accessKeySecret ";
String bucketName = "你的bucketName "; //剛纔新建的bucket名稱
String fileHost = "你的fileHost "; //在剛纔新建的bucket下面新建一個目錄,這就是那個目錄的名稱
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
// 判斷文件
if (file == null) {
return null;
}
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
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) {
logger.info("------OSS文件上傳成功------" + "https://makeromance.oss-cn-hangzhou.aliyuncs.com/" + fileUrl);
}
} catch (OSSException oe) {
logger.error(oe.getMessage());
} catch (ClientException ce) {
logger.error(ce.getErrorMessage());
} finally {
if (client != null) {
client.shutdown();
}
}
return null;
}
}
獲取endpoint:
7、新建upload.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>【基於OSS的上傳文件頁面】</title>
<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>
success.html:
<!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>
<img src="https://makeromance.oss-cn-hangzhou.aliyuncs.com/langmanji/2020-05-27/3c7a040df2ad4f6ca5f6da47373c8773-xiazaierweima.jpg"/>
</div>
</body>
</html>
三、運行項目
選擇一個文件點擊上傳:
提示上傳成功,我們看下控制檯:
輸出的是我們文件上傳的路徑,然後我們看下我們阿里雲OSS存儲裏面有沒有數據:
發現已經有了,這就是一個SpringBoot基於阿里雲OSS上傳文件的例子。