I have a firebase account and I want to upload some photos programmatically to firebase storage. To do this, I am using the google cloud java storage API. I configure the permission and others. I can successfully create buckets, blobs. However, when I tried to upload a picture, either its size is 0 or it cannot downloadable (URL is not generated). The code that I use is below;
Storage storage = StorageOptions.newBuilder().setProjectId("firebaseId")
.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream("jsonFileFor Authentication")))
.build()
.getService();
String blobName = "a.jpg";
BlobId blobId = BlobId.of(bucket.getName(), blobName);
InputStream inputStream = new FileInputStream(new File("a.jpg"));
//BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("image/jpeg").build();
BlobInfo blobInfo = BlobInfo.builder(bucket.getName(), "a.jpg").contentType("image/jpeg").build();
try (WriteChannel writer = storage.writer(blobInfo)) {
byte[] buffer = new byte[1024];
int limit;
try {
while ((limit = inputStream.read(buffer)) >= 0) {
writer.write(ByteBuffer.wrap(buffer, 0, limit));
}
} catch (Exception ex) {
// handle exception
}finally {
writer.close();
}
}
Any advice is appreciated. Regards.