Search code examples
javagoogle-app-enginecloudgoogle-cloud-storage

Upload image to Google Cloud Storage (Java)


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't have any clue how to start. Does anyone of you have experience with uploading images to Google Cloud Storage? Are there better alternatives to Google Cloud Storage?


Solution

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