0

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 ?

9
  • What does it display if you add console.log(req.file.path) just before res.status(201)....? Commented Feb 5, 2020 at 7:45
  • @SuleymanSah it displays TypeError: Cannot read property 'path' of undefined Commented Feb 5, 2020 at 7:48
  • So it means file is not available. Do you have type="file" inside your input tag? Commented Feb 5, 2020 at 7:49
  • Yes, input type is file. Commented Feb 5, 2020 at 7:49
  • What does it display when you console.log(this.state.selectedCategoryImage) just before axios.post? Commented Feb 5, 2020 at 7:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.