当前位置: 首页 > 知识库问答 >
问题:

firebase函数在成功将图像保存到firebase云存储后获得下载url

窦成荫
2023-03-14
export const publishImage = functions.https.onRequest((req, res) => {
// Convert the base64 string back to an image to upload into the Google 
// Cloud Storage bucket
const base64EncodedImageString=req.body.image.replace(/^data:image\/jpeg;base64,/, "");
const mimeType = 'image/jpeg';
const randomFileName = crypto.randomBytes(16).toString('hex') + '.jpeg';    
const imageBuffer = new Buffer(base64EncodedImageString, 'base64');

const bucket = admin.storage().bucket();

// Upload the image to the bucket
const file = bucket.file('images/' + randomFileName);
file.save(imageBuffer, {
    metadata: { contentType: mimeType },
}).then(result => {
    console.log(result);
    file.makePublic();
    file.getSignedUrl({
        action: 'read',
        expires: '03-09-2491'
    }).then(urls => {
        console.log(urls[0]);
    })
});
return res.status(200).send("NOT WORKING");    
})

如何获得下载URL?

我有点糊涂了。现在,我被困在修改后的功能更新。下面是我对管理的初始化。

 import * as admin from 'firebase-admin';
 const serviceAccount = require('./../service_account.json');

 try {   
 // admin.initializeApp(functions.config().firebase); // initial
 admin.initializeApp({
     credential: admin.credential.cert(serviceAccount),
     databaseURL: "https://vmsystem-4aa54.firebaseio.com"
 });
 } catch(e) {}
 import * as simpletest from './simpletest';
 export const testsomething = simpletest.helloWorld;

共有1个答案

佴阳曦
2023-03-14

这里没有显示所有代码(例如,如何初始化Firebase Admin SDK以创建Admin)。因此,我假设您使用项目默认凭据来初始化它,如下所示:

import * as admin from 'firebase-admin'
admin.initializeApp()

这还不足以在进入管理SDK使用云存储API时使用getSignedUrl。如果要使用getSignedUrl,则需要为在控制台中创建的专用服务帐户提供凭据。

假设您将这些凭据放在functions文件夹中名为YourServiceAccount.json的文件中,您应该使用这些凭据初始化管理SDK,如下所示:

import * as serviceAccount from 'yourServiceAccount.json';
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG)
adminConfig.credential = admin.credential.cert(<any>serviceAccount)
admin.initializeApp(adminConfig);
declare module "*.json" {
  const value: any;
  export default value;
}
 类似资料: