阿裡雲對象存儲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