简体   繁体   中英

firebase storage upload from google cloud storage java api

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.

The code is working. The problem is related to the permission. You need to set the google storage owner id as the firebase storage bucket owner. Then you can write to firebase storage bucket. I do not delete the post in case somebody search for writing firebase storage from google storage java API.

Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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