Where do I store uploaded assets using multer when deploying app

22 Views Asked by At

Okay so i have an application in which i am using multer to store the uploaded assets locally but also in cloudinary as see below:

multer.js:

const multer = require('multer')
const { v4: uuidv4 } = require('uuid')

const storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, 'uploads')
    },
    filename: function(req, file, callback){
        callback(null, uuidv4() + '-' + Date.now() + file.originalname)
    }
})

const fileFilter = (req, file, callback) => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
    if(allowedTypes.includes(file.mimetype)) {
        callback(null, true)
    }else(
        callback(null, false)
    )
}

const fileSizeFormatter = (bytes, decimal) => {
    if (bytes === 0) {
      return "0 Bytes";
    }
    const dm = decimal || 2;
    const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "YB", "ZB"];
    const index = Math.floor(Math.log(bytes) / Math.log(1000));
    return (
      parseFloat((bytes / Math.pow(1000, index)).toFixed(dm)) + " " + sizes[index]
    );
};

const photoMiddleware = multer({storage, fileFilter})

module.exports = {photoMiddleware, fileSizeFormatter}

upload function:

const upload = async (req, res) => {
    let fileData = [];
    if (req.files) {
        // Save image to cloudinary
        let uploadedFile 
        for(let i = 0; i< req.files.length; i++){
            try {
                const localFilePath = req.files[i].path
                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);
                throw new Error('Image could not be Uploaded');
            }
        }
    }
    res.json(fileData) 
}

What is happening is that when a user calls the upload function, multer store it locally in the uploads folder but also uploads it to my cloudinary account, I would then proceed to store the cloudinary link in my database as a string. This is working locally ofcourse but i am about to deploy my app on Render, My question is that since i can no longer store the pictures locally, what do i do? Is the ideal way not to store it anywhere and just keep using the cloudinary pictures link or to store it in multer memory as i saw when researching?

0

There are 0 best solutions below