gpt4 book ai didi

java - 在授予公共(public)访问权限的情况下将文件上传到 AWS S3

转载 作者:行者123 更新时间:2023-12-01 23:37:37 26 4
gpt4 key购买 nike

我有一个定义为具有公共(public)访问权限的 S3 存储桶,但是,当我将文件上传到其中并访问 URL 时,出现访问被拒绝错误:

{
Region region = Region.EU_WEST_1;
S3Client s3 = S3Client.builder()
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.region(region)
.build();

String result = putS3Object(s3, "my-bucket", "pics/15/12345.jpg", "/opt/pics/15/12345.jpg");

System.out.println(result);


}

// snippet-start:[s3.java2.s3_object_upload.main]
public static String putS3Object(S3Client s3,
String bucketName,
String objectKey,
String objectPath) {

try {
PutObjectResponse response = s3.putObject(PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build(),
RequestBody.fromBytes(getObjectFile(objectPath)));

return response.eTag();

} catch (S3Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}

// Return a byte array
private static byte[] getObjectFile(String filePath) {

FileInputStream fileInputStream = null;
byte[] bytesArray = null;

try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);

} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}

enter image description here

这是我在桶中看到的信息:

Objects are the fundamental entities that are stored in Amazon S3. In order for other people to gain access to objects, you will have to explicitly grant them permissions.

我也试过 API 的 V2

最佳答案

您的问题可能与以下事实有关:尽管您配置了对存储桶的公共(public)访问权限,可能通过取消选中其Block public access 配置选项中的所有复选框,您仍然需要 enable public access在创建对象时通过配置相应的对象 ACL 在对象本身上。

您可以在放置对象操作中指定对象的 ACL。请考虑在您的代码中进行以下修改:

    // snippet-start:[s3.java2.s3_object_upload.main]
public static String putS3Object(S3Client s3,
String bucketName,
String objectKey,
String objectPath) {

try {
PutObjectResponse response = s3.putObject(
PutObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
// this is the important modification, set a
// pre-established (canned) ACL of public-read for the object
.acl(ObjectCannedACL.PUBLIC_READ)
.build(),
RequestBody.fromBytes(getObjectFile(objectPath)));

return response.eTag();

} catch (S3Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}

请参阅Java API的相关文档和 object ACLs .

关于java - 在授予公共(public)访问权限的情况下将文件上传到 AWS S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65362080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com