Upload image to Google Cloud Storage (Java)

后端 未结 3 1852
梦谈多话
梦谈多话 2021-01-15 16:11

I want to develop a java-application (for pc) which can upload any picture to Google Cloud Storage. Although I have spent my whole evening on searching for a solution, I don

3条回答
  •  滥情空心
    2021-01-15 17:00

    You can public your file, and then the media link of the blob can access anywhere.

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

    This is my solution.

    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();
    }
    

提交回复
热议问题