SpringBoot實(shí)現(xiàn)上傳文件到AWS S3的代碼
簡單記錄一下在Springboot中上傳文件到AWS S3存儲服務(wù)的代碼。
在 application.xml中添加aws相關(guān)配置:
custom: aws: access-key: CHOBITACCESSKEY secret-key: CHOBIT/THISIS006SECRET007Key/dotORG bucket: zhyea endpoint: www.zhyea.com:80
新建一個 AwsS3Componment類來執(zhí)行上傳文件操作:
@Component
public class AwsS3Component implements InitializingBean {
@Value("${custom.aws.access-key}")
private String accessKey;
@Value("${custom.aws.secret-key}")
private String accessSecret;
@Value("${custom.aws.bucket}")
private String bucket;
@Value("${custom.aws.endpoint}")
private String endpoint;
private AmazonS3 client;
@Override
public void afterPropertiesSet() {
ClientConfiguration config = new ClientConfiguration();
config.setProtocol(Protocol.HTTP);
config.disableSocketProxy();
this.client = AmazonS3ClientBuilder
.standard()
.withClientConfiguration(config)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, accessSecret)))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName()))
.enablePathStyleAccess()
.build();
}
}
因?yàn)槭褂玫姆?wù)有設(shè)置endpoint,所以這里需要使用下面這一行完成endpoint的設(shè)置:
withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName()))
如果不設(shè)置endpoint就會收到下面這樣的報錯:
com.amazonaws.services.s3.model.AmazonS3Exception: The AWS Access Key Id you provided does not exist in our records. (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: FRDT8N0RAQFNCVDP; S3 Extended Request ID: DemEatwroXry2YN/5lyuMKDmhIi/aIz3QZPmLN0DYHeHU3oGUeOClJBcToz1J1qkcBZBfklRNs8=) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1660) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1324) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1074) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719) at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
異常信息中提示了AccessKey無效——雖然我的AccessKey是有效的。
在endpoint的這行配置中還設(shè)置了region信息。如果不需要設(shè)置endpoint,就得補(bǔ)上region的配置:
this.client = AmazonS3ClientBuilder .standard() .withClientConfiguration(config) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, accessSecret))) .withRegion(Regions.CN_NORTH_1) //Region配置 .enablePathStyleAccess() .build();
下面是執(zhí)行上傳的代碼:
/**
* 執(zhí)行文件上傳
*
* @param file 要上傳的文件的路徑
* @param key 存儲文件的路徑
* @return 文件路徑
*/
private String upload(File file, String key) {
client.putObject(new PutObjectRequest(bucket, key, file).withCannedAcl(CannedAccessControlList.PublicRead));
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
URL url = client.generatePresignedUrl(urlRequest);
return url.toString();
}
這里是通過 File實(shí)例執(zhí)行的上傳。有時候會需要直接通過文件流執(zhí)行上傳,此時可以使用下面的代碼:
private String upload(InputStream input, String key) throws IOException {
Date expireDate = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30));
ObjectMetadata metadata = new ObjectMetadata();
metadata.setHttpExpiresDate(expireDate);
metadata.setContentLength(input.available());
client.putObject(new PutObjectRequest(bucket, key, input, metadata).withCannedAcl(CannedAccessControlList.PublicRead));
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket, key);
URL url = client.generatePresignedUrl(urlRequest);
return url.toString();
}
注意這里的 setContentLength()最好配置一下。不設(shè)置會在處理的時候給出WARN。根據(jù)方法文檔也可以看到,如果不設(shè)置,在上傳的時候就會先在內(nèi)存中緩存整個信息流來計算文件長度。
大體上就是這樣了。
End!
以上就是SpringBoot實(shí)現(xiàn)上傳文件到AWS S3的代碼的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 上傳文件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
slf4j?jcl?jul?log4j1?log4j2?logback各組件系統(tǒng)日志切換
這篇文章主要介紹了slf4j、jcl、jul、log4j1、log4j2、logback的大總結(jié),各個組件的jar包以及目前系統(tǒng)日志需要切換實(shí)現(xiàn)方式的方法,有需要的朋友可以借鑒參考下2022-03-03
java算法入門之有效的括號刪除有序數(shù)組中的重復(fù)項實(shí)現(xiàn)strStr
大家好,我是哪吒,一個熱愛編碼的Java工程師,本著"欲速則不達(dá),欲達(dá)則欲速"的學(xué)習(xí)態(tài)度,在程序猿這條不歸路上不斷成長,所謂成長,不過是用時間慢慢擦亮你的眼睛,少時看重的,年長后卻視若鴻毛,少時看輕的,年長后卻視若泰山,成長之路,亦是漸漸放下執(zhí)念,內(nèi)心歸于平靜的旅程2021-08-08
list集合去除重復(fù)對象的實(shí)現(xiàn)
下面小編就為大家?guī)硪黄猯ist集合去除重復(fù)對象的實(shí)現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
JPA如何使用entityManager執(zhí)行SQL并指定返回類型
這篇文章主要介紹了JPA使用entityManager執(zhí)行SQL并指定返回類型的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
Java中JSON字符串進(jìn)行各種轉(zhuǎn)換的方法小結(jié)
Gson和Hutool的JSONUtil都是常用的用于處理JSON數(shù)據(jù)的工具庫,它們提供了簡單易用的API來進(jìn)行JSON字符串的解析、轉(zhuǎn)換和操作,下面就跟隨小編一起學(xué)習(xí)一下如果使用他們實(shí)現(xiàn)JSON字符串的各種轉(zhuǎn)換吧2024-01-01
關(guān)于Spring?Cloud實(shí)現(xiàn)日志管理模塊
這篇文章主要介紹了關(guān)于Spring?Cloud實(shí)現(xiàn)日志管理模塊問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
Spring啟動時實(shí)現(xiàn)初始化的幾種方案
這篇文章主要介紹了Spring啟動時實(shí)現(xiàn)初始化的幾種方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06

