使用multer将图像上传到Firebase存储问题

时间:2019-04-09 20:38:15

标签: node.js firebase firebase-storage multer

您好,我正在尝试使用Node.js / multer将图像上传到Firebase存储(注意:我知道我可以在客户端执行此操作,但这需要在服务器端工作)。我遇到了这个问题:

  

TypeError:storage.ref不是函数

我尝试通过添加import 'firebase/storage';来解决问题,如其他堆栈溢出所建议的那样,但这没有用。

路由器:

import {FirebaseManager, FirebaseReferences} from '../database_manager';

router.post("/:uuid/image", upload.single("file"), (req, res) => {
    const tempPath = req.file.path;
    const ext = path.extname(req.file.originalname).toLowerCase();

    if (ext === ".png" || ext === ".jpg") {
        FirebaseManager.upload_image(FirebaseReferences.Images, 'test', req.file)
        res.status(200).contentType("text/plain").end("File uploaded!");
    } else {
        try {
            fs.unlinkSync(tempPath);
        } catch (err) {
            res.status(400).send(err.message);
        }
        res.status(403).contentType("text/plain").end("Only .png/jpg files are allowed!");
    }
  }
);

Firebase Manager:

var admin = require('firebase-admin');
import firebase = require('firebase/app');
import 'firebase/database';
import 'firebase/storage';

// Access the real-time database in the initialized application.
const FirebaseApp: firebase.app.App = admin.initializeApp({
  credential: admin.credential.cert({
    projectId: '',
    clientEmail: '',
    privateKey: ''
  }),
  databaseURL: 'https://.firebaseio.com'
});
const db: firebase.database.Database = FirebaseApp.database();
const storage: firebase.storage.Storage = FirebaseApp.storage();

export function upload_image(ref: FirebaseReferences, filename: string,
        file: any): string {

        var upload_loc = ref.toString() + '/' + filename;
        var upload_ref = storage.ref().child(upload_loc);

        upload_ref.put(file).then(function(snapshot) {
            snapshot.ref.getDownloadURL().then(function(downloadURL) {
                console.log('File available at', downloadURL);
                return downloadURL;
            });
        }, function(error) {
            console.log("FirebaseManager, upload_image(): " + error);
            throw error;
        });

        return 'error';
}

还将Express.Multer.File类型上传到“存储”工作吗?如果不能,该如何将其转换为File的类型?

node 10.2.1
multer 1.4.1
firebase ^5.7.3
firebase-admin ^6.5.0

1 个答案:

答案 0 :(得分:2)

您在storageBucket的配置中缺少admin.initializeApp

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "<BUCKET_NAME>.appspot.com"
});

https://firebase.google.com/docs/storage/admin/start