繁体   English   中英

将图片上传到Google Cloud Storage(Java)

[英]Upload image to Google Cloud Storage (Java)

我想开发一个Java应用程序(适用于PC),可以将任何图片上传到Google Cloud Storage。 尽管我整夜都在寻找解决方案,但是我不知道如何开始。 你们中有人有将图像上传到Google Cloud Storage的经验吗? 是否有更好的Google Cloud Storage替代品?

有一个漂亮的Java API可用于使用Google Cloud,包括存储: http : //googlecloudplatform.github.io/google-cloud-java/0.10.0/index.html

以下是使用此库上传和下载文件的示例桌面应用程序: https : //github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-examples/src/main/java/com/google /cloud/examples/storage/StorageExample.java

Google Cloud Storage有很多文档,指南和教程。 这是所有内容的根源: https//cloud.google.com/storage/docs/

  @Override
  public String uploadImage(String fileName , String filePath,String fileType) throws IOException {
    Bucket bucket = getBucket("sample-bucket");
    InputStream inputStream = new FileInputStream(new File(filePath));
    Blob blob = bucket.create(fileName, inputStream, fileType);
    log.info("Blob Link:"+blob.getMediaLink());
    return blob.getMediaLink();
  }


  private Bucket getBucket(String bucketName) throws IOException {
    GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(CREDENTIALS_PATH))
        .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
    Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
    Bucket bucket = storage.get(bucketName);
    if (bucket == null) {
      throw new IOException("Bucket not found:"+bucketName);
    }
    return bucket;
  }

CREDENTIALS_PATH,在设置服务帐户时进行下载,请确保用户有权将其上传到存储桶中。

您可以公开文件,然后Blob的媒体链接可以在任何地方访问。

https://cloud.google.com/storage/docs/access-control/making-data-public

这是我的解决方案。

try {
    FileInputStream serviceAccount =
            new FileInputStream("firebaseKey/serviceAccountKey.json");

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://xxxxx.firebaseio.com")
            .build();
    FirebaseApp fireApp = FirebaseApp.initializeApp(options);

    StorageClient storageClient = StorageClient.getInstance(fireApp);
    InputStream testFile = new FileInputStream(file.getPath());
    String blobString = "NEW_FOLDER/" + "FILE_NAME.jpg";
    Blob blob = storageClient.bucket("xxxxxx.appspot.com")
                    .create(blobString, testFile , Bucket.BlobWriteOption.userProject("xxxxxxx"));
    blob.getStorage().createAcl(blob.getBlobId(), Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
    System.out.println(blob.getMediaLink());
} catch (Exception e){
    e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM