Search code examples
javascriptnode.jsreactjsexpressmulter

File not uploading in Express JS using Multer


I am creating API using express JS. Now, I have a router which will be used to upload image using multer.

Here is my router :

const multer = require('multer');

module.exports = (app) => {
  const DIR = './public/';

  const storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, DIR);
    },
    filename: (req, file, cb) => {
      cb(null , file.originalname);
    }
  });

  const upload = multer({ storage: storage });

  // I have also tried this but not working
  // const upload = multer({ dest: 'uploads/' });

  app.post('/upload', upload.single('image'), (req, res, next) => {
    res.status(201).json({
      message: "File uploaded successfully"
    });
  });
}

Now, from my reactjs app I am calling this router using axios like this :

const headers = {
  "Content-Type": "multipart/form-data"
}
const body = new FormData();
body.append('image', this.state.selectedCategoryImage);
axios.post('http://localhost:3000/upload', body, { headers }).then((res) => {
  console.log(res);
}).catch((err) => {
  console.log(err);
});

In above code this.state.selectedCategoryImage is a selected image from html <input> tag.

Now, When I call this api I am getting my response "file uploaded successfully", but I am not able to see my uploaded image anywhere in public directory. My image is not uploading.

Please anyone can help me what's the issue ?


Solution

  • Pass file Object not URL

    URL.createObjectURL(file) // it return file url that you can use to show file preview

    For upload file, send actual file in axios API as you got from file input

    var file = event.target.files[0]; // return actual file

    this way it actually send file object.