上传到 Firebase 时调整图像大小或压缩图像

Rob*_*ell 1 javascript node.js google-cloud-storage firebase busboy

以下谷歌云功能可以正确上传图像,但我还想压缩图像,以避免因上传大文件而产生不必要的费用。任何建议将不胜感激!!!代码如下:

exports.uploadImage = (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 })

  let imageToBeUploaded = {}
  let imageFileName

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    if (mimetype !== `image/jpeg` && mimetype !== `image/png`) {
      return res.status(400).json({ error: `Not an acceptable file type` })
    }

    // my.image.png => ['my', 'image', 'png']
    const imageExtension = filename.split(".")[filename.split(".").length - 1]
    // 32756238461724837.png
    imageFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${imageExtension}`
    const filepath = path.join(os.tmpdir(), imageFileName)
    imageToBeUploaded = { filepath, mimetype }
    file.pipe(fs.createWriteStream(filepath))
  })

  busboy.on("finish", () => {
    admin
      .storage()
      .bucket(config.storageBucket)
      .upload(imageToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToBeUploaded.mimetype
          }
        }
      })
      .then(() => {
        const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
        return db.doc(`/users/${req.user.uid}`).update({ imageUrl })
      })
      .then(() => {
        return res.json({ message: "image uploaded successfully" })
      })
      .catch(err => {
        console.error(err)
        return res.status(500).json({ error: "something went wrong" })
      })
  })
  busboy.end(req.rawBody)
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以在客户端设置最大文件大小并在提交前进行验证。目前,任何人都可以启用扩展程序(在 Firebase 控制台菜单上)来自动调整上传到项目的 Firebase 存储桶的任何图像的大小。您只需选中调整大小完成后删除原始文件的选项即可。更多信息请参见:https ://firebase.google.com/products/extensions/storage-resize-images