生活随笔
收集整理的這篇文章主要介紹了
【测试Demo】JavaAPI操作阿里云对象存储(OSS)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
阿里云對象存儲 阿里云官網(wǎng)點擊
阿里云對象存儲OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存儲服務(wù),提供99.9999999999%(12個9)的數(shù)據(jù)持久性,99.995%的數(shù)據(jù)可用性。多種存儲類型供選擇,全面優(yōu)化存儲成本。【源于官網(wǎng)】
首先來看注冊和手動申請阿里云OSS倉庫
1 點擊進(jìn)入管理控制臺
2 控制臺頁面
3 創(chuàng)建自己的Bucket
4 按照下面的方式創(chuàng)建Bucket
5 點擊確定即可,經(jīng)過以上過程,即成功申請了阿里云OSS云存儲倉庫
下面介紹使用Java API 操作 OSS
1 配置依賴,參考
java 8及以下,使用Maven在pom.xml中引入
<dependency
><groupId
>com.aliyun.oss
</groupId
><artifactId
>aliyun-sdk-oss
</artifactId
><version
>3.10.
2</version
>
</dependency
>
如果是Java9及以上或者用Eclipse開發(fā)具體可參見官方文檔
2 Java API操作OSS
多種編程語言的API 點擊進(jìn)入
使用Java API操作OSS其實有官方文檔可以借鑒,點擊JavaAPI文檔,在文檔中,不難發(fā)現(xiàn),每一個功能前面都有一系列的Access賬號的認(rèn)證,如下圖所示
下面說說賬號怎么設(shè)置
1 點擊進(jìn)入 OSS 控制臺 進(jìn)入
選擇訪問控制 RAM 進(jìn)入,其實AccessKey也可以,但是主要影響整個倉庫的安全性,所以推薦使用 箭頭指向的那個
2 點擊進(jìn)去,創(chuàng)建用戶
3 創(chuàng)建完用戶后,進(jìn)行權(quán)限設(shè)置
4 在搜索框中輸入 oss 將四個 OSS的權(quán)限,都加進(jìn)去。
如果加入成功,加入過的會變灰
使用程序進(jìn)行訪問OSS
1 將上面的用戶信息配置到項目的 application.yml
加入下面的代碼段
alioss:endpoint: oss-cn-your location.aliyuncs.comaccessKeyId: your AccessKeyIdaccessKeySecret: your AccessKeySecretbucketName: your bucket name
其中endpoint在
2 創(chuàng)建OSS實體類
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix
= "alioss")
@Component
@Data
public class OssEntity {private String endpoint
;private String accessKeyId
;private String accessKeySecret
;private String bucketName
;
}
3 創(chuàng)建Service 接口
import java.io.IOException;public interface AliOssService {void createBucket();String upload(MultipartFile file
);void download(String fileName
) throws IOException;void listFile();void deleteFile(String fileName
);
}
4 ServiceImpl類
可借鑒OSS Java API 開發(fā)文檔
import com.aliyun.oss.OSS
;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.s.system.entity.OssEntity;
import com.s.system.service.AliOssService;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.UUID
;
@Service
public class AliOssServiceImpl implements AliOssService, InitializingBean {@Autowiredprivate OssEntity ossEntity
;private String endpoint
;private String accessKeyId
;private String accessKeySecret
;private String bucketName
;@Overridepublic void createBucket() {OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);if (ossClient
.doesBucketExist(bucketName
)) {throw new RuntimeException(bucketName
+ "在對象存儲的Bucket列表中已經(jīng)存在");}ossClient
.createBucket(bucketName
);ossClient
.shutdown();}@Overridepublic String upload(MultipartFile file
) {String uploadUrl
= null;try {OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);if (!ossClient
.doesBucketExist(bucketName
)) {ossClient
.createBucket(bucketName
);ossClient
.setBucketAcl(bucketName
, CannedAccessControlList.PublicRead);}InputStream inputStream
= file
.getInputStream();String datePath
= new DateTimeLiteralExpression.DateTime().toString("yyyy/MM/dd");String original
= file
.getOriginalFilename();String fileName
= UUID
.randomUUID().toString().replaceAll("-", "");String fileType
= original
.substring(original
.lastIndexOf("."));String newName
= fileName
+ fileType
;fileName
= datePath
+ "/" + newName
;ObjectMetadata objectMetadata
= new ObjectMetadata();objectMetadata
.setObjectAcl(CannedAccessControlList.PublicRead);objectMetadata
.setContentType(getcontentType(fileName
.substring(fileName
.lastIndexOf("."))));ossClient
.putObject(bucketName
, fileName
, inputStream
, objectMetadata
);ossClient
.shutdown();Date expiration
= new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);uploadUrl
= ossClient
.generatePresignedUrl(bucketName
, fileName
, expiration
).toString();} catch (IOException e
) {e
.printStackTrace();}return uploadUrl
.substring(0, uploadUrl
.indexOf("?"));}@Overridepublic void download(String fileName
) throws IOException {String objectName
= fileName
;OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);OSSObject ossObject
= ossClient
.getObject(bucketName
, objectName
);InputStream content
= ossObject
.getObjectContent();if (content
!= null) {BufferedReader reader
= new BufferedReader(new InputStreamReader(content
));while (true) {String line
= reader
.readLine();if (line
== null) {break;}System.out
.println("\n" + line
);}content
.close();}ossClient
.shutdown();}@Overridepublic void listFile() {OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);ObjectListing objectListing
= ossClient
.listObjects(bucketName
);for (OSSObjectSummary objectSummary
: objectListing
.getObjectSummaries()) {System.out
.println(" - " + objectSummary
.getKey() + " " +"(size = " + objectSummary
.getSize() + ")");}ossClient
.shutdown();}@Overridepublic void deleteFile(String fileName
) {String objectName
= fileName
;OSS ossClient
= new OSSClientBuilder().build(endpoint
, accessKeyId
, accessKeySecret
);ossClient
.deleteObject(bucketName
, objectName
);ossClient
.shutdown();}@Overridepublic void afterPropertiesSet() throws Exception {endpoint
= ossEntity
.getEndpoint();accessKeyId
= ossEntity
.getAccessKeyId();accessKeySecret
= ossEntity
.getAccessKeySecret();bucketName
= ossEntity
.getBucketName();}public static String getcontentType(String FilenameExtension) {if (FilenameExtension.equalsIgnoreCase(".bmp")) {return "image/bmp";}if (FilenameExtension.equalsIgnoreCase(".gif")) {return "image/gif";}if (FilenameExtension.equalsIgnoreCase(".jpeg") ||FilenameExtension.equalsIgnoreCase(".jpg") ||FilenameExtension.equalsIgnoreCase(".png")) {return "image/jpg";}if (FilenameExtension.equalsIgnoreCase(".html")) {return "text/html";}if (FilenameExtension.equalsIgnoreCase(".txt")) {return "text/plain";}if (FilenameExtension.equalsIgnoreCase(".vsd")) {return "application/vnd.visio";}if (FilenameExtension.equalsIgnoreCase(".pptx") ||FilenameExtension.equalsIgnoreCase(".ppt")) {return "application/vnd.ms-powerpoint";}if (FilenameExtension.equalsIgnoreCase(".docx") ||FilenameExtension.equalsIgnoreCase(".doc")) {return "application/msword";}if (FilenameExtension.equalsIgnoreCase(".xml")) {return "text/xml";}return "image/jpg";}
}
5 測試
import com.s.system.entity.OssEntity;
import com.s.system.service.AliOssService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class OssTest {@Autowiredprivate OssEntity ossEntity
;@Autowiredprivate AliOssService aliOssService
;@Testpublic void contextLoads(){aliOssService
.createBucket();System.out
.println(ossEntity
.toString());}}
測試通過后,可以發(fā)現(xiàn),這個錯誤主要是在 aplication.yml 中已經(jīng)存在了 該 bucket,可以自行再將 application.yml 中的 bucketName: your bucket name 定義一個新的名字,就可以通過了。這也就說明OSS Demo 測試通過,可以進(jìn)行下面的開發(fā)了。
總結(jié)
以上是生活随笔為你收集整理的【测试Demo】JavaAPI操作阿里云对象存储(OSS)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。