How to get the file out of a buffer in nodejs/express?

18 Views Asked by At

Okay so i am using multer to upload my pictures and then save it to cloudinary. Since i am deploying the application, i am trying to use multer memory storage to upload the file however it has been giving me issues.

After researching online, this is what i have, however it isnt working for me:

const upload = async (req, res) => {
    let fileData = [];
    if (req.files) {
        // Save image to cloudinary
        let uploadedFile 
        let buffer
        let localFilePath
        for(let i = 0; i< req.files.length; i++){
            try {
                buffer = req.files[i].buffer
                localFilePath = fs.readFileSync(buffer, { encoding: 'utf8' })
                uploadedFile = await cloudinary.uploader.upload(localFilePath, {
                    folder: "products",
                    resource_type: "image",
                })
                fileData.push({
                    fileName: req.files[i].originalname,
                    filePath: uploadedFile.secure_url,
                })

            } catch (error) {
                res.status(500);
                console.log({'error': error}, {'files': req.files}, {'path': localFilePath}, {'buffer': buffer})
                throw new Error('Image could not be Uploaded');
            }
        }
    }
    res.json(fileData) 
}

As seen above, i am logging out the variables to understand what is happening:

error: The argument 'path' must be a string or Uint8Array without null bytes.

files: [
    {
      fieldname: 'images',
      originalname: 'GAIzjxXXYAArOMQ.jpeg',
      encoding: '7bit',
      mimetype: 'image/jpeg',
      buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 05 03 04 04 04 03 05 04 04 04 05 05 05 06 07 0c 08 07 07 07 07 0f 0b 0b 09 ... 47506 more bytes>,
      size: 47556
    }
]

path: undefined 

buffer: buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43 00 05 03 04 04 04 03 05 04 04 04 05 05 05 06 07 0c 08 07 07 07 07 0f 0b 0b 09 ... 47506 more bytes>

From what i can see, the buffer looks normal to me, but the path is returning undefined for some reason. what am i doing wrong?

0

There are 0 best solutions below