aws s3 文件上传代码
首先,确保您已经在AWS上创建了一个S3存储桶,并拥有相应的访问密钥和密钥ID。这些凭据将用于在Java代码中进行身份验证。
接下来,需要在Java项目中添加AWS SDK的依赖。可以使用Maven或Gradle进行依赖管理。以下是一个Maven的示例依赖项:
<dependencies><dependency><groupId>software.amazon.awssdk</groupId><artifactId>s3</artifactId><version>2.17.4</version></dependency>
</dependencies>
示例代码:
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;import java.io.File;
import java.nio.file.Paths;public class S3Uploader {public static void main(String[] args) {// 设置AWS区域和凭据提供程序Region region = Region.US_EAST_1;DefaultCredentialsProvider credentialsProvider = DefaultCredentialsProvider.create();// 创建S3客户端S3Client s3Client = S3Client.builder().region(region).credentialsProvider(credentialsProvider).build();// 指定要上传的文件和目标存储桶String bucketName = "your-bucket-name";String objectKey = "your-object-key";File file = new File("path/to/your/file");// 创建上传请求PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(bucketName).key(objectKey).build();// 设置文件元数据ObjectMetadata metadata = ObjectMetadata.builder().contentType("application/octet-stream").build();putObjectRequest = putObjectRequest.toBuilder().metadata(metadata).build();// 执行上传操作PutObjectResponse putObjectResponse = s3Client.putObject(putObjectRequest, Paths.get(file.getAbsolutePath()));// 打印上传结果System.out.println("文件上传成功,ETag: " + putObjectResponse.eTag());// 设置文件访问权限s3Client.putObjectAcl(PutObjectAclRequest.builder().bucket(bucketName).key(objectKey).acl(ObjectCannedACL.PUBLIC_READ).build());// 获取文件URLString fileUrl = s3Client.utilities().getUrl(GetUrlRequest.builder().bucket(bucketName).key(objectKey).build()).toExternalForm();// 打印文件URLSystem.out.println("文件URL: " + fileUrl);}
}
在上述代码中,需要将 your-bucket-name
替换为自己的S3存储桶名称, your-object-key
替换为想要为上传文件指定的对象键, path/to/your/file
替换为要上传的文件的路径。
代码示例中还包括了设置文件元数据、设置文件访问权限以及获取文件URL的步骤。这些步骤可以帮助您更好地控制上传文件的属性和访问权限。