从Node js上传Firebase存储中具有0字节的Imagen

时间:2018-12-21 18:32:03

标签: node.js firebase-storage firebase-admin

我正在尝试将图像从Node.js上传到Firebase存储, 我按照以下说明在文档中添加了Firebase,并且一切运行良好,但是当图像在存储中时,大小为0字节,您看不到预览。

这是我的代码:

const uploadImageToStorage = (file,filename) => {
    let prom = new Promise((resolve, reject) => {
        if (!file) {
            reject('No image file');
        }
        let newFileName = `${file.originalname}_${Date.now()}`;
        let fileUpload = bucket.file(newFileName);
        const blobStream = fileUpload.createWriteStream({
            metadata: {
                contentType: file.mimetype
            }
        });

        blobStream.on('error', (error) => {
            reject('Something is wrong! Unable to upload at the moment.');
        });

        blobStream.on('finish', () => {
            // The public URL can be used to directly access the file via HTTP.
            const url = `https://storage.googleapis.com/${bucket.name}/${fileUpload.name}`;
            resolve(url);
        });

        blobStream.end(file.buffer);
    });
    return prom;
}

这是我的app.post方法:

app.post('/Upload_img',multer.single("file"), function (req, res) {

    console.log("Upload Imagennes");
    let url = "";
    let file= req.file;
    if (file) {
        uploadImageToStorage(file,file.name).then((success) => {
            url = success;
            res.status(200).send(url);
        }).catch((error) => {
            console.error(error);
        });
    }



}

存储空间:

enter image description here

1 个答案:

答案 0 :(得分:0)

我成功使用您的uploadImageToStorage函数上传了png文件。我直接调用它,而没有使用multer

(async () => {
  const buffer = fs.readFileSync('./android.png');
  const file = {
    originalname: 'android.png',
    mimetype: 'image/png',
    buffer,
  }
  try {
    return await uploadImageToStorage(file, file.originalname);
  } catch (err) {
    console.log(err);
  }
})();

这按预期工作。因此,问题可能出在Express.js代码或multer中。尝试在服务器代码中记录req.filereq.file.buffer,并查看其中是否包含预期的数据。