Soyo
Soyo

Reputation: 21

Multer doesn't save the file

Multer does not save the file and I cannot see any logs... The folder is empty, no any files.

The image data is actually sent to the server as its console logged: Screenshot of req.files from log

What am I doing wrong? Please help me find

const express = require('express');
const router = express.Router();
const path = require('path');
const multer = require('multer');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    console.log('destination') // can't see this log
    cb(null, './uploads/');
  },
  filename: (req, file, cb) => {
    console.log('filename') // can't see this log
    const ext = file.mimetype.split("/")[1];
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const uploadImage = multer({
  storage,
  limits: { fieldSize: 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    console.log('log!')  // can't see this log
    const ext = path.extname(file.originalname);
    if (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png') {
      console.log('not log!')  // can't see this log
      const err = new Error('Extention');
      err.code = 'EXTENTION';
      return cb(err);
    }
    console.log('log!') // can't see this log
    cb(null, true);
  }
}).single('photo');

router.post('/image', async (req, res) => {
  console.log(req.files) // can see this log

  uploadImage(req, res, err => {
    console.log('upload') // can see this log

    let error = '';
    if (err) {
      console.log(err)
      if (err.code === 'LIMIT_FILE_SIZE') {
        error = 'Max 500kb!';
      }
      if (err.code === 'EXTENTION') {
        error = 'Only jpg and png!';
      }
    }

    res.json({
      ok: !error,
      error
    });
  })
});

Upvotes: 1

Views: 566

Answers (2)

Soyo
Soyo

Reputation: 21

Multer finally gave an error, so the problem was resolved... The problem was that the names of these fields are different:

Server: .single('pic');

And in the request to the server: formData.append('pic', file);

Upvotes: 1

Jagadeesh K
Jagadeesh K

Reputation: 886

The code seems to work fine for me but I just had to manually create the uploads directory.

I used postman to test this and the picture appeared in my uploads directory.

# Console Output
SERVER RUNNING ON 3000
undefined
log!
log!
destination
filename
upload

Upvotes: 0

Related Questions