Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To upload Images/Files to Firebase storage in Java?

I am working in a functionality where i need to upload an Image/File to firebase storage using java and expose it as an API. I have already achieved this functionality in angular 4 typescript. But now i need this method as an Java Rest API, so that my peer can also consume the same method instead of writing a new one. So is there any API or methods to write the image to firebase storage ?

like image 517
Pradeep Anand Avatar asked Mar 06 '23 05:03

Pradeep Anand


2 Answers

Try this:

FirebaseOptions options = FirebaseOptions.builder()
                    .setCredentials(credential)
                    .setDatabaseUrl(projectUrl)
                    .setStorageBucket("YOUR BUCKET LINK")
                    .build();

    FirebaseApp fireApp = FirebaseApp.initializeApp(options);

    StorageClient storageClient = StorageClient.getInstance(fireApp);
            InputStream testFile = new FileInputStream("YOUR FILE PATH");
            String blobString = "NEW_FOLDER/" + "FILE_NAME.EXT";        

    storageClient.bucket().create(blobString, testFile , Bucket.BlobWriteOption.userProject("YOUR PROJECT ID"));
like image 77
Erick Cabral Avatar answered Mar 07 '23 19:03

Erick Cabral


If the Java project is running in a trusted environment (such as their development machine, a server you control, or Cloud Functions), they can use the Firebase Admin SDK to access Cloud Storage.

See the Firebase Admin SDK documentation on how to get started, and then the Google Cloud Storage documentation for Java clients for more. Specifically have a look at the sample of uploading a file in Java:

BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
like image 35
Frank van Puffelen Avatar answered Mar 07 '23 18:03

Frank van Puffelen