赞
踩
Python 实现方式:https://blog.csdn.net/qq_33811662/article/details/80710268
使用 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);
- }
- }
原文链接:https://blog.csdn.net/qq_33811662/article/details/80710318
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。