springboot集成oss物件存盤服務
- 小白一枚 如若描述有誤還請評論區指點痛批
1. 環境準備:
登錄阿里云oss物件存盤控制臺:傳送門
前提環境搭建請參考阿里云oss物件存盤官方檔案:傳送門
2.創建springboot專案匯入 oss相關依賴
<!--OSS圖片服務器 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
請根據當前版本狀況進行調整(博主測驗時間:2021/4/18有效)
3.創建application.properties檔案并配置
application.properties配置項:
# EndPoint
aliyun.oss.file.endpoint=xxxxxxxxxxxxxxxx
# KeyId
aliyun.oss.file.keyid=xxxxxxxxxxxxxxxxxx
# KeySecret
aliyun.oss.file.keysecret=xxxxxxxxxxxxxxxxxxxxxx
# bucketName
aliyun.oss.file.bucketname=xxxxxxxxxxxxxxxxxx
# # 訪問圖片的固定前綴
aliyun.oss.file.httpsprefix=xxxxxxxxxxxxxx
如上五個配置如果找不到請看下圖:
EndPoint

KeyId和 KeySecret

bucketName

訪問圖片的固定前綴

只要相關依賴存在以下代碼均可直接copy
3.創建工具類
package com.oss;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class OssConstant implements InitializingBean {
/** 從組態檔中讀取bucketName */
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
/** 從組態檔中讀取存盤檔案的地址前綴 */
@Value("${aliyun.oss.file.httpsprefix}")
private String ossHttpsPrefix;
public static String BUCKET_NAME;
public static String OSS_HTTPS_PREFIX;
@Override
public void afterPropertiesSet() throws Exception {
BUCKET_NAME = bucketName;
OSS_HTTPS_PREFIX = ossHttpsPrefix;
}
}
4.創建配置類
package com.oss;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
@Configuration
public class OssConfig {
/** 從組態檔中讀取endPoint */
@Value("${aliyun.oss.file.endpoint}")
private String ossEndpoint;
/** 從組態檔中讀取KeyId */
@Value("${aliyun.oss.file.keyid}")
private String keyId;
/** 從組態檔中讀取KeySecret */
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Bean
public OSSClient ossClient(){
return (OSSClient) new OSSClientBuilder().build(ossEndpoint, keyId, keySecret);
}
}
5.創建Controller
package com.oss;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
@RestController
@RequestMapping("/oss")
public class OssController {
@Autowired
private OSSClient ossClient;
/**
* 上傳圖片到OSS
* @param file 圖片檔案
* @return 圖片訪問地址
*/
@PostMapping("/upload")
public String ossUpload(MultipartFile file){
System.out.println("檔案上傳"+file);
// 獲取原始檔案名(我一般都是用UUID生成新的檔案名)
String fileName = file.getOriginalFilename();
// 檔案夾名(可以用模塊名)
String folder = "liuchengyin";
// 檔案夾名(根據日期來存盤)
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 檔案名 - 使用UUID生成
String fileNameUUID = UUID.randomUUID().toString().replaceAll("-", "");
if (fileName != null){
// 獲取原始檔案名的后綴,如.jpg .png
fileNameUUID = folder+ "/" + format + "/" + fileNameUUID + fileName.substring(fileName.lastIndexOf("."));
} else {
// 一般來說這種情況是不存在的
fileNameUUID = folder+ "/" + format + "/" + fileNameUUID + ".jpg";
}
try {
ossClient.putObject(OssConstant.BUCKET_NAME, fileNameUUID, file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
// 回傳檔案訪問地址 - 這里可以封裝一個物件,回傳訪問地址和檔案名(也就是fileNameUUID)
// 這個檔案名(fileNameUUID)可以用于查詢是否存在、洗掉等操作
return OssConstant.OSS_HTTPS_PREFIX + "/" + fileNameUUID;
}
/**
* 洗掉OSS里的檔案/檔案夾(檔案夾內不能有檔案)
* @param fileName 檔案名 - 完整檔案名包括檔案夾名,如:liuchengyin/2021-03-23/f624048f7ca8466881f825365e3308d4.jpg
* @return
*/
@PostMapping("/delete")
public String ossDelete(String fileName){
ossClient.deleteObject(OssConstant.BUCKET_NAME, fileName);
return "洗掉成功!";
}
/**
* 批量洗掉OSS里的檔案
* @param fileNames 檔案名集合 - 完整檔案名包括檔案夾名,如:liuchengyin/2021-03-23/f624048f7ca8466881f825365e3308d4.jpg
* @return
*/
@PostMapping("/deleteBatch")
public List<String> ossDeleteBatch(@RequestBody List<String> fileNames){
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(OssConstant.BUCKET_NAME).withKeys(fileNames));
// 回傳的就是洗掉成功的圖片名集合(圖片不存在,也會回傳)
return deleteObjectsResult.getDeletedObjects();
}
/**
* 查詢OSS里的檔案是否存在
* @param fileName 檔案名 - 完整檔案名包括檔案夾名,如:liuchengyin/2021-03-23/f624048f7ca8466881f825365e3308d4.jpg
* @return 是否存在:true or false
*/
@GetMapping("/exist")
public Boolean isExist(String fileName) {
return ossClient.doesObjectExist(OssConstant.BUCKET_NAME, fileName);
}
}
更多需求可以參考阿里云 oss官方api:傳送門
拿到圖片訪問url后如果不能訪問請設定如下:

訪問鏈接為: https:// 拿到的鏈接
舉例:https://xiaoou1.oss-cn-beijing.aliyuncs.com/liuchengyin/2021-04-18/bd95d88734af43b0b90e5879fe451bf4.jpg
注釋:根據oss檔案規定通過檔案URL訪問圖片時,默認是下載行為,因為博主很窮只有一個域名 所以暫時沒有系結 所以您在訪問時默認是下載圖片的行為而不是在線預覽 如果你有html基礎你可以使用img標簽來展示圖片
注釋:
這里詳情請看官方檔案
訪問控制(Resource Access Management,RAM)是阿里云提供的一項管理用戶身份與資源訪問權限的服務,使用
RAM,您可以創建、管理 RAM 子用戶(例如員工、系統或應用程式),并可以控制這些 RAM
子用戶對資源的操作權限,當您的企業存在多用戶協同操作資源時,使用 RAM
可以讓您避免與其他用戶共享云賬號密鑰,按需為用戶分配最小權限,從而降低企業資訊安全風險, 了解 訪問控制 RAM 產品,
博主之前填寫的是阿里云 API 的密鑰 但是官方是非常建議大家填寫子用戶的密鑰

傳送門:RAM訪問控制臺
創建用戶并為用戶賦予權限
此時注意注意注意 !!!!!!!!!!!!!!!!!!!!
此時注意注意注意 !!!!!!!!!!!!!!!!!!!!
此時注意注意注意 !!!!!!!!!!!!!!!!!!!!
使用子用戶的KeyId和KeySecret要注意當你創建完成后它會提示你在你創建的時候顯示一次之后不做顯示 而此時你就要妥善保管如果丟失則重新創建一次
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277798.html
標籤:其他
