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
新建一個(gè) AwsS3Componment類來執(zhí)行上傳文件操作:
@Componentpublic 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就會收到下面這樣的報(bào)錯(cuò):
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í)行的上傳。有時(shí)候會需要直接通過文件流執(zhí)行上傳,此時(shí)可以使用下面的代碼:
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è)置會在處理的時(shí)候給出WARN。根據(jù)方法文檔也可以看到,如果不設(shè)置,在上傳的時(shí)候就會先在內(nèi)存中緩存整個(gè)信息流來計(jì)算文件長度。
大體上就是這樣了。
End!
以上就是SpringBoot實(shí)現(xiàn)上傳文件到AWS S3的代碼的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 上傳文件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python math模塊的基本使用教程2. 如何用python開發(fā)Zeroc Ice應(yīng)用3. ASP錯(cuò)誤捕獲的幾種常規(guī)處理方式4. python基于opencv批量生成驗(yàn)證碼的示例5. npm下載慢或下載失敗問題解決的三種方法6. ASP編碼必備的8條原則7. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法8. python用pyecharts實(shí)現(xiàn)地圖數(shù)據(jù)可視化9. python軟件測試Jmeter性能測試JDBC Request(結(jié)合數(shù)據(jù)庫)的使用詳解10. python uuid生成唯一id或str的最簡單案例
