【问题标题】:Amazon s3 file Public on uploadAmazon s3 文件上传时公开
【发布时间】:2023-04-08 12:23:01
【问题描述】:

我需要调用 withCannedAcl 方法。它将图像转换为公开阅读的 ENUM,因此当图书图像在 Bucket 中注册时,它们将具有可读的公开可见性,并且所有用户都可以查看图像。如何将方法插入到我的文件保护程序文件中?

这里是我找到的 withCannedAcl 方法:

.withCannedAcl(CannedAccessControlList.PublicRead));

这是我必须在其中插入该方法的 filesaver.java(可能在 s3.putObject():? 内)。我试过了,还是不行。

@RequestScoped
public class FileSaver {

private static final String CONTENT_DISPOSITION = "content-disposition";

private static final String FILENAME_KEY = "filename=";

@Inject
private AmazonS3Client s3;    

public String write(String baseFolder, Part multipartFile) {
    AmazonS3Client s3 = client();
    String fileName = extractFilename(multipartFile.getHeader(CONTENT_DISPOSITION));
    try {
        s3.putObject("superkovalev", fileName,
                multipartFile.getInputStream(),                    
                new ObjectMetadata());            
                return "https://s3.amazonaws.com/xxxxxxxxxxxxxx/"                            
                +fileName;
    } catch (AmazonClientException | IOException e) {
        throw new RuntimeException(e);
    }
}

 private AmazonS3Client client() {
    AWSCredentials credentials = new BasicAWSCredentials("xxxxxxxx ",
            xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    AmazonS3Client newClient = new AmazonS3Client(credentials, new 
     ClientConfiguration());
    newClient.setS3ClientOptions(new 
     S3ClientOptions().withPathStyleAccess(true));
    return newClient;
   }

  private String extractFilename(String contentDisposition) {

    if (contentDisposition == null) {
        return null;
    }
    int startIndex = contentDisposition.indexOf(FILENAME_KEY);
    if (startIndex == -1) {
        return null;
    }
    String filename = contentDisposition.substring(startIndex
            + FILENAME_KEY.length());
    if (filename.startsWith("\"")) {
        int endIndex = filename.indexOf("\"", 1);
        if (endIndex != -1) {
            return filename.substring(1, endIndex);
        }
    } else {
        int endIndex = filename.indexOf(";");
        if (endIndex != -1) {
            return filename.substring(0, endIndex);
        }
    }
    return filename;
}

public AmazonS3Client getS3() {
    return s3;
}

public void setS3(AmazonS3Client s3) {
    this.s3 = s3;
}

 }

【问题讨论】:

标签: java amazon-s3


【解决方案1】:

这是问题的答案:

Policy bucket_policy = new Policy().withStatements(
new Statement(Statement.Effect.Allow)
    .withPrincipals(Principal.AllUsers)
    .withActions(S3Actions.GetObject)
    .withResources(new Resource(
        "arn:aws:s3:::" + bucket_name + "/*")));

https://docs.aws.amazon.com/pt_br/sdk-for-java/v1/developer-guide/examples-s3-bucket-policies.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2010-12-04
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多