SpringBoot實現上傳檔案到AWS S3的程式碼
阿新 • • 發佈:2020-10-27
簡單記錄一下在Springboot中上傳檔案到AWS S3儲存服務的程式碼。
在 application.xml
中新增aws相關配置:
custom: aws: access-key: CHOBITACCESSKEY secret-key: CHOBIT/THISIS006SECRET007Key/dotORG bucket: zhyea endpoint: www.zhyea.com:80
新建一個 AwsS3Componment
類來執行上傳檔案操作:
@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(); } }
因為使用的服務有設定endpoint,所以這裡需要使用下面這一行完成endpoint的設定:
withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint,Regions.CN_NORTH_1.getName()))
如果不設定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的這行配置中還設定了region資訊。如果不需要設定endpoint,就得補上region的配置:
this.client = AmazonS3ClientBuilder .standard() .withClientConfiguration(config) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey,accessSecret))) .withRegion(Regions.CN_NORTH_1) //Region配置 .enablePathStyleAccess() .build();
下面是執行上傳的程式碼:
/** * 執行檔案上傳 * * @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
例項執行的上傳。有時候會需要直接通過檔案流執行上傳,此時可以使用下面的程式碼:
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,input,metadata).withCannedAcl(CannedAccessControlList.PublicRead)); GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucket,key); URL url = client.generatePresignedUrl(urlRequest); return url.toString(); }
注意這裡的 setContentLength()
最好配置一下。不設定會在處理的時候給出WARN。根據方法文件也可以看到,如果不設定,在上傳的時候就會先在記憶體中快取整個資訊流來計算檔案長度。
大體上就是這樣了。
End!
以上就是SpringBoot實現上傳檔案到AWS S3的程式碼的詳細內容,更多關於SpringBoot 上傳檔案的資料請關注我們其它相關文章!