Java:實現向 AWS 的 S3 上傳檔案
阿新 • • 發佈:2019-02-01
使用 java 包去連線 s3 並且向 s3 上傳檔案,需要有 s3 的包,此處我用的是 maven 專案去匯入 s3 的包,在 pom.xml 中加入如下內容
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.347</version>
</dependency>
此時 maven 會自動匯入相關的依賴包:
然後需要有一個 aws 的 s3 許可權的一個 IAM 帳號,需要得到 access_key 和 secret_key
最後是程式碼部分:
import java.io.File; import java.io.IOException; import java.net.URL; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.transfer.TransferManager; public class UploadTest { AmazonS3 s3; String AWS_ACCESS_KEY = "xxxxxxxx"; // 【你的 access_key】 String AWS_SECRET_KEY = "xxxxxxxx"; // 【你的 aws_secret_key】 String bucketName = "xxxxxxx"; // 【你 bucket 的名字】 # 首先需要保證 s3 上已經存在該儲存桶 static { s3 = new AmazonS3Client(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY)); s3.setRegion(Region.getRegion(Regions.US_EAST_1)); // 此處根據自己的 s3 地區位置改變 } public String uploadToS3(File tempFile, String remoteFileName) throws IOException { try { String bucketPath = bucketName + "/upload" ; s3.putObject(new PutObjectRequest(bucketPath, remoteFileName, tempFile) .withCannedAcl(CannedAccessControlList.PublicRead)); GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName); URL url = s3.generatePresignedUrl(urlRequest); return url.toString(); } catch (AmazonServiceException ase) { ase.printStackTrace(); } catch (AmazonClientException ace) { ace.printStackTrace(); } return null; } @Test public void test(){ File uploadFile = new File("c:/test.txt"); String uploadKey = "test" uploadToS3(uploadFile,uploadKey); } }