阿里雲對象存儲OSS服務——上傳/刪除/獲取圖片
1. 準備工作
- 開通對象存儲 OSS服務
- 創建AccessKey(使用阿里雲OSS SDK時需要使用到)
- 創建Bucket(輸入唯一的Bucket名字,選擇合適的區域,其他選項默認)
- 創建Spring Boot項目
- 推薦使用Postman測試後端API,Postman的下載及使用參考 https://blog.csdn.net/fxbin123/article/details/80428216
- 注意:使用Postman測試上傳圖片功能時,需要將請求體(Body)的類型設爲form-data
2. 上傳圖片
// 未對異常進行處理
@PostMapping(value = "/image")
public void uploadImage(MultipartFile file) {
// MultipartFile代表HTML中form data方式上傳的文件
// EndPoint以上海爲例
String endPoint = "oss-cn-shanghai.aliyuncs.com";
// 阿里雲API祕鑰
String accessKeyId = "<your access key id>";
String accessKeySecret = "<your access key secret>";
String bucketName = "<bucket name>";
OSSClient client = new OSSClient(endPoint, accessKeyId, accessKeySecret);
client.putObject(bucketName, imageName, new ByteArrayInputStream(file.getBytes()));
client.shutdown();
}
3. 刪除圖片
// 未對異常進行處理
@DeleteMapping(value = "/image/{imageName}")
public void deleteImage(@PathVariable String imageName) {
// EndPoint以上海爲例
String endPoint = "oss-cn-shanghai.aliyuncs.com";
// 阿里雲API祕鑰
String accessKeyId = "<your access key id>";
String accessKeySecret = "<your access key secret>";
String bucketName = "<bucket name>";
OSSClient client = new OSSClient(endPoint, accessKeyId, accessKeySecret);
client.deleteObject(bucketName, imageName);
client.shutdown();
}
4. 獲取圖片
// 未對所有異常進行處理
@GetMapping(value = "/image/{imageName}")
public byte[] getImage(@PathVariable String imageName) {
// EndPoint以上海爲例
String endPoint = "oss-cn-shanghai.aliyuncs.com";
// 阿里雲API祕鑰
String accessKeyId = "<your access key id>";
String accessKeySecret = "<your access key secret>";
String bucketName = "<bucket name>";
OSSClient client = new OSSClient(endPoint, accessKeyId, accessKeySecret);
OSSObject image = client.getObject(bucketName, imageName);
InputStream content = image.getObjectContent();
if (content != null) {
try {
// 設置一個足夠大的buffer用於存儲圖片的比特數據
int length = 1920 * 1260 * 3;
byte[] buf = new byte[length];
int size = 0;
int temp;
while ((temp = content.read()) != -1) {
buf[size] = (byte) temp;
size++;
}
content.close();
// 對緩衝區進行裁剪後,將圖片以字節數組的形式返回
return Arrays.copyOf(buf, size);
} catch (IOException e) {
System.out.println("exception");
return null;
}
}
client.shutdown();
return null;
}
5. 測試獲取圖片功能
將內容拷貝後粘貼到Spring Boot項目的src/main/resources/static目錄的某個文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Image</title>
</head>
<body style="margin: 0;">
<!-- 測試獲取OSS圖片功能是否正確 -->
<img src="http://localhost:80/image/<imageName>"/>
</body>
</html>
阿里雲對象存儲 OSS官方文檔: https://help.aliyun.com/product/31815.html?spm=5176.8466032.0.0.7e8714505JnJY6