admin管理员组

文章数量:1316023

The following google cloud function properly uploads an image, but I would also like to press the image as to avoid unnecessary charges due to large files being uploaded. Any suggestions would be greatly appreciated!!! the code is as follows:

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 = `/${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)
}

The following google cloud function properly uploads an image, but I would also like to press the image as to avoid unnecessary charges due to large files being uploaded. Any suggestions would be greatly appreciated!!! the code is as follows:

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./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)
}
Share Improve this question edited Mar 3, 2020 at 20:10 Doug Stevenson 318k36 gold badges455 silver badges472 bronze badges asked Mar 3, 2020 at 19:57 Rob TerrellRob Terrell 2,5624 gold badges21 silver badges47 bronze badges 3
  • 2 Image files are already pressed. If you want more pression, resize the image to be smaller, or re-press the image using a different algorithm. – Doug Stevenson Commented Mar 3, 2020 at 20:10
  • yes i understand they are already pressed but i would like to repress so people arent uploading massive high pixelated images. how exactly can i write that logic – Rob Terrell Commented Mar 3, 2020 at 20:12
  • There are libraries out there that allow you to perform image manipulation programmatically. I suggest doing some research to find one and experiment with it. – Doug Stevenson Commented Mar 3, 2020 at 20:24
Add a ment  | 

1 Answer 1

Reset to default 6

You can set a maximum file size client-side and validate before submission. At the moment, anyone can enable an extension (on the Firebase Console Menu) to automatically resize any image uploaded to the project's firebase storage bucket. You just have to check the option to delete the original file after resizing is plete. More info here: https://firebase.google./products/extensions/storage-resize-images

本文标签: javascriptResizing or compressing image on upload to FirebaseStack Overflow