简体   繁体   中英

Cloud Storage API doesn't work when deploy on Google Cloud Functions using Firebase

This work perfectly in local serve with firebase :

const gCloudConfig = {
  projectId: 'XXXX-X1234',
  keyFilename: './key.json'
}
const Storage = require('@google-cloud/storage')(gCloudConfig);
const storageBucket = Storage.bucket(bucketUrl);

storageBucket.upload(file.path, {destination: file.name})
  .then(() => {
    //
  });

But this doesn't work when i deploy to firebase :

const Storage = require('@google-cloud/storage')();
const storageBucket = Storage.bucket(bucketUrl);

storageBucket.upload(file.path, {destination: file.name})
  .then(() => {
    //
  });

I put this line after the admin.initializeApp(...) , since i saw that it fixed the problem for someone, but it still doesn't work.

I've tried a lot of stuff :

const gCloudConfig = { projectId: 'XXXX-X1234' };
const gCloudConfig = { key: API_KEY };
const gCloudConfig = { key: API_KEY, projectId: 'XXXX-X1234' };
const gCloudConfig = functions.config().firebase;

I'm kinda lost, please help me !

It's easier if you just initialize the Firebase Admin SDK with its default credentials, then access the Cloud Storage APIs via that. There's no need to initialize Storage on its own.

const admin = require('firebase-admin')
admin.initializeApp()
const bucket = admin.storage().bucket()
bucket.upload(localPath, {
    destination: remotePath
})

Here, bucket is your project default storage bucket, just like you would have gotten it from the Cloud Storage API.

Note that the no-argument init of the Admin SDK is available when using firebase-functions@1.0.0 or later (current 1.0.2).

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