0

I'm trying to upload an image to my directory using Postman. I am using Nodejs and multer as a middleware.

However, I get an ENOENT error: EnoEnt

My question is as follows, why does my code give double \\, and what can I do to change double backslashes to forward slash in the pathname?

My code so far is:

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '.test/');
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});
router.post('/', upload.single('productImage'), (req, res, next) => {
  console.log(req.file);
...
...
...

I have tried using the .replace() method without any success.

const multer = require('multer');

let destination = '.uploads/';

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, destination.replace('\\','/'));
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});

I have also tried searching similar posts here on StackOverflow, e.g trying this posts answer Error: ENOENT: no such file or directory,

haycon
  • 25
  • 8

2 Answers2

0

You can use path.normalize('\\dsgsd\\sdgsdg') method. You can find it in official NodeJS documentation https://nodejs.org/api/path.html#path_path_normalize_path

const multer = require('multer');
const { normalize } = require('path')

let destination = '.uploads/';

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, normalize(destination));
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});
0

I found the answer after a bit of googling.

The problem was not the double \\, they are allowed, the problem was in the way the filename was saved. The filename was of a datestring, and was saved in the format: 2020-11-25T12:15something, the problem is that Windows OS does not accept files with the character ":".

Solution would be to replace this line of code :

cb(null, new Date().toISOString() + file.originalname);

with

cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);

Original answer here

haycon
  • 25
  • 8