Amazon s3文件已上传公共

时间:2018-11-22 17:01:45

标签: java amazon-s3

我需要调用withCannedAcl方法。它将图像作为公众阅读的ENUM进行转换,因此,将图书图像注册到存储桶中时,它们将具有可读的公共可见性,并且所有用户都可以查看图像。如何将方法插入我的filesaver文件中?

这是我发现的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;
}

 }

1 个答案:

答案 0 :(得分:0)

这是问题的答案:

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