當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot整合阿里云OSS上传文件
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot整合阿里云OSS上传文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、需求分析
文件上傳是一個非常常見的功能,就是通過IO流將文件寫到另外一個地方,這個地方可以是項目下的某個文件夾里,或者是本地電腦某個盤下面,還可以是云服務OSS里面,這里就是我要講到的OSS,我寫的是基于阿里云的。
二:環境搭建
我這里是用的Springboot.Thymeleaf插件,為了在html頁面實現文件上傳功能。
1、首先開通阿里云OSS存儲,這里不多說了。
2、創建一個Bucket
這個bucket名稱是等下參數里面要用到的。區域可以選擇你那邊的區域。
3、創建好之后返回剛才的頁面,點擊Access Key,來獲取accessKeyId、accessKeySecret這兩個參數
4、Maven依賴(Thymeleaf、OSS)
5、新建一個UpLoadController.java
*** @descibe oss*/ @Controller public class UpLoadController {private static final String TO_PATH = "upload";private static final String RETURN_PATH = "success";@Autowiredprivate 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);// 上傳到OSSString uploadUrl = aliyunOSSUtil.upLoad(newFile);}}} catch (Exception ex) {ex.printStackTrace();}return RETURN_PATH;} }6、新建AliyunOSSUtil.java
/*** @descibe oss*/ @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:
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上傳文件的例子。
總結
以上是生活随笔為你收集整理的SpringBoot整合阿里云OSS上传文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java基础day17
- 下一篇: controller的异常处理以及ser