获取 firebase admin 文件上传的进度

Get progress of firebase admin file upload

我正在尝试使用 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 分钟视频的位置。目前,它只是一个 activity 指示器,用户只是坐着等待,没有任何通知。如果有任何帮助,我会在前端使用 React Native。非常感谢任何帮助!

我能够更轻松地在客户端实施...但它与图像和视频上传进度配合得很好。在后端,我使用的是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);
          });
        });
export const uploadFile = (
  folderPath,
  fileName,
  file,
  generateDownloadURL = true,
  updateInformationUploadProgress
) => {
  return new Promise((resolve, reject) => {
    try {
      const storageRef = firebaseApp.storage().ref(`${folderPath}/${fileName}`)
      const uploadTask = storageRef.put(file)

      uploadTask.on(
        'state_changed',
        snapshot => {
          if (updateInformationUploadProgress) {
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100
            updateInformationUploadProgress({
              name: fileName,
              progress: progress,
            })
          }
        },
        error => {
          console.log('upload error: ', error)
          reject(error)
        },
        () => {
          if (generateDownloadURL) {
            uploadTask.snapshot.ref
              .getDownloadURL()
              .then(url => {
                resolve(url)
              })
              .catch(error => {
                console.log('url error: ', error.message)
                reject(error)
              })
          } else {
            resolve(uploadTask.snapshot.metadata.fullPath)
          }
        }
      )
    } catch (error) {
      reject(error)
    }
  })
}