亚马逊s3存储工具类java实现批量上传文件
时间: 2023-08-16 08:09:09 浏览: 140
以下是使用Java语言实现批量上传文件到AWS S3存储的示例代码:
```java
import java.io.File;
import java.util.List;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectRequest;
public class S3Util {
private static final String S3_ENDPOINT = "your-s3-endpoint-url";
private static final String S3_REGION = "your-s3-region";
private static final String S3_ACCESS_KEY = "your-s3-access-key";
private static final String S3_SECRET_KEY = "your-s3-secret-key";
private static final String S3_BUCKET_NAME = "your-s3-bucket-name";
public static void uploadFiles(List<File> files) {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(S3_ENDPOINT, S3_REGION))
.withCredentials(new DefaultAWSCredentialsProviderChain())
.build();
try {
for (File file : files) {
String key = file.getName();
PutObjectRequest request = new PutObjectRequest(S3_BUCKET_NAME, key, file);
s3Client.putObject(request);
}
} catch (AmazonServiceException e) {
e.printStackTrace();
} catch (SdkClientException e) {
e.printStackTrace();
}
}
}
```
使用时,只需传入需要上传的文件列表即可:
```java
List<File> files = new ArrayList<>();
files.add(new File("file1"));
files.add(new File("file2"));
S3Util.uploadFiles(files);
```
在上述代码中,我们使用了AWS SDK的`AmazonS3`客户端,通过`withEndpointConfiguration`方法设置S3的Endpoint URL和Region,`withCredentials`方法设置S3的Access Key和Secret Key,`build`方法创建S3客户端。在上传文件时,我们使用了`PutObjectRequest`对象,其中包含了需要上传的文件、存储桶名称和对象名称,通过`putObject`方法将文件上传到S3存储中。
希望对你有所帮助!
阅读全文