You can use this code right here
var admin = require("firebase-admin");
const uuid = require('uuid-v4');
// CHANGE: The path to your service account
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: "<BUCKET_NAME>.appspot.com"
});
var bucket = admin.storage().bucket();
var filename = "path/to/image.png"
async function uploadFile() {
const metadata = {
metadata: {
// This line is very important. It's to create a download token.
firebaseStorageDownloadTokens: uuid()
},
contentType: 'image/png',
cacheControl: 'public, max-age=31536000',
};
// Uploads a local file to the bucket
await bucket.upload(filename, {
// Support for HTTP requests made with `Accept-Encoding: gzip`
gzip: true,
metadata: metadata,
});
console.log(`${filename} uploaded.`);
}
uploadFile().catch(console.error);
To successfully run this code, you will need to:
- Add the Firebase Admin SDK to Your Server
- Install uuid-v4
- Replace
"path/to/serviceAccountKey.json"
with the path to your own service account. Here is a guide to get yours.
- Replace
<BUCKET_NAME>
with the name of your default bucket. You can find this name in the Storage section of your Firebase Console. The bucket name must not contain gs://
or any other protocol prefixes. For example, if the bucket URL displayed in the Firebase Console is gs://bucket-name.appspot.com
, pass the string bucket-name.appspot.com
to the Admin SDK.
- Replace
"path/to/image.png"
with the path to your own image.
- If needed, adjust the
contentType
in the metadata
accordingly.
Just to let you know, whenever you upload an image using Firebase Console, an access token will be automatically generated. However, if you upload an image using any Admin SDK or gsutil you will need to manually generate this access token yourself. That's why it is very important the uuid
part
Firebase Support says that this is being fixed, but I think anyone having this problem should go this way instead of waiting for Firebase to fix this.