首页 > 解决方案 > 获取 Firebase 管理文件上传的进度

问题描述

我正在尝试使用 admin sdk 将 1 分钟的视频上传到 Firebase 存储桶存储的进度。我已经看到了很多关于使用 firebase.storage().ref.child ..... 但我无法使用 admin sdk 做到这一点,因为它们没有相同的功能。这是我的文件上传:

exports.uploadMedia = (req, res) => {
    const BusBoy = require('busboy');
    const path = require('path');
    const os = require('os');
    const fs = require('fs');

    const busboy = new BusBoy({ headers: req.headers, limits: { files: 1, fileSize: 200000000 } });

    let mediaFileName;
    let mediaToBeUploaded = {};

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {

        if(mimetype !== 'image/jpeg' && mimetype !== 'image/png' && mimetype !== 'video/quicktime' && mimetype !== 'video/mp4') {
            console.log(mimetype);
            return res.status(400).json({ error: 'Wrong file type submitted, only .png, .jpeg, .mov, and .mp4 files allowed'})
        }

        // my.image.png
        const imageExtension = filename.split('.')[filename.split('.').length - 1];
        
        //43523451452345231234.png
        mediaFileName = `${Math.round(Math.random()*100000000000)}.${imageExtension}`;
        const filepath = path.join(os.tmpdir(), mediaFileName);
        mediaToBeUploaded = { filepath, mimetype };
        file.pipe(fs.createWriteStream(filepath));

        file.on('limit', function(){
            fs.unlink(filepath, function(){
                return res.json({'Error': 'Max file size is 200 Mb, file size too large'});
            });
        });
    });
    busboy.on('finish', () => {
        admin
        .storage()
        .bucket()
        .upload(mediaToBeUploaded.filepath, {
            resumable: false,
            metadata: {
                metadata: {
                    contentType: mediaToBeUploaded.mimetype
                }
            }
        })
        .then(() => {
            const meadiaUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${mediaFileName}?alt=media`;
            return res.json({mediaUrl: meadiaUrl});
        })
        .catch((err) => {
            console.error(err);
            return res.json({'Error': 'Error uploading media'});
        });
    });
    req.pipe(busboy);
}

这现在可以正常工作,但唯一的问题是用户看不到他们的 1 或 2 分钟视频上传的位置。目前,它只是一个活动指示器,用户只是坐着等待,没有任何通知。如果有任何帮助,我会在前端使用本机反应。将不胜感激任何帮助!

标签: node.jsreact-nativegoogle-cloud-storagefirebase-storagefirebase-admin

解决方案


我能够在客户端更容易地实现......但它与图像和视频上传进度完美配合。在后端,我使用的是 admin sdk,但我最初使用的是 firebase sdk。

        this.uploadingMedia = true;
        const imageExtension = this.mediaFile.split('.')[this.mediaFile.split('.').length - 1];
        const mediaFileName = `${Math.round(Math.random()*100000000000)}.${imageExtension}`;
        const response = await fetch(this.mediaFile);
        const blob = await response.blob();
        const storageRef = storage.ref(`${mediaFileName}`).put(blob);
        storageRef.on(`state_changed`,snapshot=>{
          this.uploadProgress = (snapshot.bytesTransferred/snapshot.totalBytes);
        }, error=>{
          this.error = error.message;
          this.submitting = false;
          this.uploadingMedia = false;
          return;
        },
        async () => {
          storageRef.snapshot.ref.getDownloadURL().then(async (url)=>{
            imageUrl = [];
            videoUrl = [url];
            this.uploadingMedia = false;
            this.submitPost(imageUrl, videoUrl);
          });
        });

推荐阅读