0

trying to upload an image using multer and getting this error

ENOENT: no such file or directory, open 'C:\Users\Marwa\mern-stack\uploads\images\74.jpeg' POST /api/users/signup 500 23.065 ms - 1711 RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: ENOENT at ServerResponse.writeHead (_http_server.js:248:11)

any ideas why this error happened?

this is the file-upload middleware and the image should be stored in uploads/images folder

const multer = require("multer");
const MIME_TYPE_MAP = {
  "image/png": "png",
  "image/jpeg": "jpeg",
  "image/jpg": "jpg",
};

const fileUpload = multer({
  limits: { fileSize: 2 * 1024 * 1024 },
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, "uploads/images");
    },
    filename: (req, file, cb) => {
      const ext = MIME_TYPE_MAP[file.mimetype];
      cb(null, Math.floor(Math.random() * 100) + "." + ext);
    },
  }),
  fileFilter: (req, file, cb) => {
    const isValid = !!MIME_TYPE_MAP[file.mimetype];
    let error = isValid ? null : new Error("Invalid mime type!");
    cb(error, isValid);
  },
});
module.exports = fileUpload;

then I pass this middleware to route I want to add image for (signup)

router.post(
  "/signup",
  fileUpload.single("image"),
  [
    check("name").not().isEmpty(),
    check("email").isEmail(),
    check("password").isLength({ min: 6 }),
  ],
  createUser
);
coder
  • 64
  • 6

1 Answers1

0

Make sure you create the directory uploads/images in the root folder the error says "ENOENT: no such file or directory"..

I had a different error message but it's still about the "ENOENT".

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: ENOENT
    at new NodeError (node:internal/errors:399:5)
    at ServerResponse.writeHead (node:_http_server:344:11)
    at ServerResponse._implicitHeader (node:_http_server:335:8)
    at write_ (node:_http_outgoing:912:9)
    at ServerResponse.end (node:_http_outgoing:1019:5)
Harsha Murupudi
  • 579
  • 1
  • 6
  • 19