Nadin Hasan
Nadin Hasan

Reputation: 29

What is the correct way to make multer work with Node and Express here?

I am trying to create a route through which I can upload photos. However as I made so,e changes it stopped working and I am not sure how to make it work.

const multer = require('multer');

// MULTER STORAGE
const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, '/upload');
  },
  filename: (req, file, cb) => {
    const ext = file.mimetype.split('/')[1];
    // Saving format: user-UserId-DateStamp.ext
    //e.g user-608d55c7e512b74ee00791de-1621992912638.jpeg
    cb(null, `user-${req.body.userId}-${Date.now()}.${ext}`);
  },
});

//MULTER FILTER
const multerFilter = (req, file, cb) => {
  //mimetype always starts with image/ then png or jpeg or..
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cb(new AppError('You are only allowed to upload image files.', 400), false);
  }
};

const uploadDirectory = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
});

//exports.uploadPhoto = uploadDirectory.single('photo');

//app.use(express.static('./uploads'));

// INCLUDE ERROR CLASS AND ERROR CONTROLLER
const AppError = require('../utils/appError.js');
const errorController = require('./errorController.js');
const { Mongoose } = require('mongoose');

The main problem Im guessing is in this block

//UPLOAD PHOTO
exports.uploadPhoto = uploadDirectory(async (req, res) => {
  console.log(req.body);
  console.log(req.file);

  try {
    const newPhoto = await photoModel.create(req.file);
    newPhoto.save().then((result) => {
      console.log('Saved');
      res.status(201).json({
        status: 'success',
        // data: JSON.parse(JSON.stringify(newPhoto.file)),
      });
    });
  } catch (err) {
    console.log('Error in upload');
    errorController.sendError(err, req, res);
  }
}).single('photo');

Can anybody let me know how to correctly write the exports.uploadPhoto

Originally the last function looked like this

exports.uploadPhoto = async (req, res) => {
  console.log(req.body);
  console.log(req.file);

  try {
    const newPhoto = await photoModel.create(req.file);
    newPhoto.save().then((result) => {
      console.log('Saved');
      res.status(201).json({
        status: 'success',
        // data: JSON.parse(JSON.stringify(newPhoto.file)),
      });
    });
  } catch (err) {
    console.log('Error in upload');
    errorController.sendError(err, req, res);
  }
};

Upvotes: 2

Views: 109

Answers (1)

Maxim Orlov
Maxim Orlov

Reputation: 2592

The multer middleware function, in your case uploadDirectory, is usually used before other middleware functions/controllers where you have your business logic (e.g. uploadPhoto).

app.post('/upload', uploadDirectory.single('photo'), uploadPhoto);

Keep your original uploadPhoto function and with the above code you'll have access to the data and file through reg.body and req.file, respectively.

This Request Parsing in Node.js Guide (it's free) will help you with file uploads in Node.js.

Upvotes: 1

Related Questions