Search code examples
javascriptnode.jsuploadmulter

Image file upload with node.js


I'm trying to adapt my code to upload files, but I'm not getting it, I looked in the community and I didn't understand, I'm still new to this. It always falls on the error json return, do you know what it can be? File where you have the logic

async img(request, response){
    multer({
        storage: multer.diskStorage({
            destination: (req, file, cb) => {
                cb(null, "./Uploads")
        },
        filename: (req, file, cb) => {

            cb(null, Date.now().toString() + '-' + file.originalname)

        },
        fileFilter: (req, file, cb) => {
            const extensionImg = ['image/png', 'image/jpg', 'image/jpeg'].find
            (formatPermitted => formatPermitted == file.mimetype)

            if(extensionImg){
                return cb(null, true)
            }
                return cb(null, false)
            } 

       })

    }).single('image')

    if(request.file){
        return response.status(200).json({erro: false, message: "ok"});
    }else{
        return response.status(400).json({erro: true, message: "error"});
    }
} 

File where the route is

const IncidentsController = require('./controllers/IncidentsController');

const routes = express.Router();

routes.post('/uploads', IncidentsController.img)

Solution

  • multer(...).single(...) returns a middleware function. That middleware function that it returns has to be actually called in order to do something.

    Typically, you would define the middleware outside a request handler and then use it as middleware on one or more request handlers.

     const imgMulterMiddleware = multer({
        storage: multer.diskStorage({
            destination: (req, file, cb) => {
                cb(null, "./Uploads")
        },
        filename: (req, file, cb) => {
    
            cb(null, Date.now().toString() + '-' + file.originalname)
    
        },
        fileFilter: (req, file, cb) => {
            const extensionImg = ['image/png', 'image/jpg', 'image/jpeg'].find
            (formatPermitted => formatPermitted == file.mimetype)
    
            if(extensionImg){
                return cb(null, true)
            }
                return cb(null, false)
            } 
    
       })
    
    }).single('image');
    

    Then, use that middleware as needed:

    routes.post('/uploads', imgMulterMiddleware, (req, res) => {
         // do something with req.file here which will be set
         // by the middleware if it was successful
    
        if (req.file) {
            res.json({erro: false, message: "ok"});
        } else {
            res.status(400).json({erro: true, message: "error"});
        }
    });