Jezyk Danzowki
Jezyk Danzowki

Reputation: 229

Multer is storing in local AppData and not in specified directory

I am using Multer with my MEAN2 stack and I have got file uploading working fine through ng2-uploader.

But I am trying to upload it to the server so i can then parse the csv file to json, but that is not the issue.

The file uploads fine ... but it uploads it to AppData\Local\Temp, here is the file information once uploaded:

[ { fieldname: 'file',
    originalname: 'sfgsgsfrfs.jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    destination: 'C:\\Users\\Jezyk\\AppData\\Local\\Temp',
    filename: 'z83yrcprp4m8azfflxr.jpg',
    path: 'C:\\Users\\Jezyk\\AppData\\Local\\Temp\\z83yrcprp4m8azfflxr.jpg',
    size: 120850 } ]

and here is my code that I am using to store the file:

const upload = multer({
    dest: './server/uploads/',
    storage: multer.diskStorage({
        filename: (req, file, cb) => {
            let ext = path.extname(file.originalname);
            cb(null, `${Math.random().toString(36).substring(7)}${ext}`);
        }
    })
});

router.route('/upload').post(upload.any(), (req, res) => {
    console.log(req.files);
    res.json(req.files.map(file => {
        let ext = path.extname(file.originalname);
        return {
            originalName: file.originalname,
            filename: file.filename
        }
    }));
});

Any idea why it is doing so?

Upvotes: 1

Views: 823

Answers (1)

mscdex
mscdex

Reputation: 106696

You need to add a destination callback if using an explicit, configured storage instance:

const upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, __dirname + '/server/uploads/')
    },
    filename: (req, file, cb) => {
      let ext = path.extname(file.originalname);
      cb(null, `${Math.random().toString(36).substring(7)}${ext}`);
    }
  })
});

Upvotes: 3

Related Questions