Google Cloud存储Java XML API文件上传并标记上传的文件公开

时间:2015-04-20 12:12:39

标签: java google-cloud-storage

我使用Google Cloud storage Java XML API将文件从客户端上传到Google Cloud Bucket,该文件已成功上传,但我希望上传的文件可公开访问(希望文件公开 - 读取权限),如何在上传的文件上设置public-read ACL,从而使其可公开访问。这是我使用的代码

httpTransport = GoogleNetHttpTransport.newTrustedTransport();


String p12Content = Files.readFirstLine(new File("key.p12"), Charset.defaultCharset());
            Preconditions.checkArgument(!p12Content.startsWith("Please"), p12Content);
            //[START snippet]
            // Build a service account credential.
Path path = Paths.get(MyFilePath);
    byte[] byteArray = java.nio.file.Files.readAllBytes(path);
HttpContent contentsend = new ByteArrayContent("text/plain", byteArray );

GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
                .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))

                .build();
            // Set up and execute a Google Cloud Storage request.
String URI = "https://storage.googleapis.com/" + BUCKET_NAME + "/myfile";
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
HttpRequest request = requestFactory.buildPutRequest(url,contentsend);
HttpResponse response = request.execute();

1 个答案:

答案 0 :(得分:2)

加入" x-goog-acl"带有值" public-read"的标题,如下所示:

request.setHeader("x-goog-acl", "public-read");

有关更多信息,请查看以下文档页面:

https://cloud.google.com/storage/docs/reference-headers#xgoogacl https://cloud.google.com/storage/docs/access-control