0

I am having trouble uploading an image to the db after cropping. I am able to upload the file on Postman, but can't figure out how to do it after cropping and getting it returned as a base64.

Here is my route that works with uploading a raw file, but not the base64:

exports.uploadProfileMedia = (req, res) => {
    const BusBoy = require("busboy")
    const path = require("path")
    const os = require("os")
    const fs = require("fs")

    let mediaFileName
    let mediaToBeUploaded = {}
    let generatedToken = uuidv4()

    const busboy = new BusBoy({ headers: req.headers })

    busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
        console.log(file, "before")
        if (
            mimetype !== "image/jpeg" &&
            mimetype !== "image/png" &&
            mimetype !== "image/heic"
        ) {
            return res.status(400).json({ error: "Wrong file type submitted" })
        }

        const mediaExtension = filename.split(".")[
            filename.split(".").length - 1
        ]
        mediaFileName = `${Math.round(
            Math.random() * 100000000000
        ).toString()}.${mediaExtension}`
        const filepath = path.join(os.tmpdir(), mediaFileName)
        mediaToBeUploaded = { filepath, mimetype }

        file.pipe(fs.createWriteStream(filepath))
        console.log(file, "after")
    })

    busboy.on("finish", () => {
        admin
            .storage()
            .bucket()
            .upload(mediaToBeUploaded.filepath, {
                resumable: false,
                metadata: {
                    metadata: {
                        contentType: mediaToBeUploaded.mimetype,
                        firebaseStorageDownloadTokens: generatedToken
                    }
                }
            })
            .then(() => {
                const mediaUrl = `https://firebasestorage.googleapis.com/v0/b/${firebaseConfig.storageBucket}/o/${mediaFileName}?alt=media&token=${generatedToken}`
                return db
                    .doc(`/users/${req.user.username}`)
                    .update({ mediaUrl })
            })
            .then(() => {
                return res
                    .status(201)
                    .json({ message: "Media uploaded successfully" })
            })
            .catch((err) => {
                console.error(err)
                return res.status(500).json({ error: err.code })
            })
    })

    busboy.end(req.rawBody)
}

Here is where I pass in a base64 after cropping:

    const uploadProfileMedia = (formData) => {
        axios.defaults.headers.common["Authorization"] = localStorage.getItem(
            "FBIdToken"
        )
        axios
            .post("/api/user/media", formData)
            .then((res) => {})
            .catch((err) => console.log(err))
        console.log(formData, "form")
    }

Here is a snippet of the above console.log():

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDREN

Here is the function which calls the uploadProfileMedia():

const showCroppedImage = useCallback(async () => {
        console.log(imageSrc, "imgsrc")
        try {
            const croppedImage = await getCroppedImg(
                imageSrc,
                croppedAreaPixels
            )
            setCroppedImage(croppedImage)
            uploadProfileMedia(croppedImage)
            console.log(croppedImage, "showcroppedImage")
        } catch (e) {
            console.error(e)
        }
    }, [imageSrc, croppedAreaPixels])
Nathan Sutherland
  • 190
  • 1
  • 2
  • 14
  • at which point is the log you shared presented? I assume it is in the `console.log(formData, "form")`, if so, how can you access it's value in the request? You could try to do something like what is described in this [community answer](https://stackoverflow.com/a/38935990/12857703) once you get the Base64 in your request to build it as a file and then keep the same code you already have. – Ralemos Feb 17 '21 at 16:12
  • @RafaelLemos, You are correct, on the log. It is passed through the showCroppedImage() I just added. – Nathan Sutherland Feb 17 '21 at 19:00
  • Would something like [this](https://stackoverflow.com/a/31111376/12857703) work in your case? – Ralemos Feb 18 '21 at 14:02

0 Answers0