AMAZON S3
使用官方SDK進行資料交換,
先安裝必要資料
POM.XML
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.767</version> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-kms --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-kms</artifactId> <version>1.11.767</version> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-core --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-core</artifactId> <version>1.11.767</version> </dependency> <!-- https://mvnrepository.com/artifact/com.amazonaws/jmespath-java --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>jmespath-java</artifactId> <version>1.11.767</version> </dependency>
上傳物件
String access = "access"; //ex: AKIA3PGEPUAAAAAABBBB String secret = "secret"; //ex: W3pIE45y64DAjeRXyBUQAAAAAAAAAABBBBBBBBBB Regions regions = Regions.AP_EAST_1; String bucket = "bucket"; String fileName = "test/data.jpg"; //檔案(包含資料夾) //憑證 AWSCredentials creds = new BasicAWSCredentials(access, secret); //建立連線 AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(regions) .withCredentials(new AWSStaticCredentialsProvider(creds)) .build(); //資料設定 PutObjectRequest request = new PutObjectRequest(bucket, fileName, new File("C:\\Users\\aaa\\Desktop\\logo.jpg")); //Metadata ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType("image/jpg"); request.setMetadata(metadata); //ACL //https://docs.aws.amazon.com/zh_tw/AmazonS3/latest/dev/acl-overview.html request.setCannedAcl(CannedAccessControlList.PublicRead); //開始傳送 s3Client.putObject(request);
取得檔案路徑
String access = "access"; //ex: AKIA3PGEPUAAAAAABBBB String secret = "secret"; //ex: W3pIE45y64DAjeRXyBUQAAAAAAAAAABBBBBBBBBB Regions regions = Regions.AP_EAST_1; String bucket = "bucket"; String fileName = "test/data.jpg"; //檔案(包含資料夾) //憑證 AWSCredentials creds = new BasicAWSCredentials(access, secret); //建立連線 AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(regions) .withCredentials(new AWSStaticCredentialsProvider(creds)) .build(); //s3路徑 String fileUrl = s3Client.getUrl(bucket, fileName).toString();
取得物件