Home > Net >  Problem while Uploading File in Mongo via Multer, NodeJS
Problem while Uploading File in Mongo via Multer, NodeJS

Time:04-30

I am trying to add a pictire to the MongoDB via Multer and NodeJS. The Multer storage is created. The middleware based on Multer called upload is inserted into the POST request. But when I carry out POST request, req.file is undefined. What is the reason for that?

routes:

const express = require('express');
const Menu = require("../models/menu");
const Image = require("../models/image");
const router = express.Router();
const multer = require("multer");

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

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

const getMenu = (req, res) => {
    Menu
      .find()
      .then((menu) => res.status(200).json(menu))
      .catch((error) => console.log("Ops"));
  }


router.get('/api/menu', getMenu);

router.post("/upload", upload.single("articleImage"), (req, res) => {
  console.log("request----------------", req.file) // UNDEFINED
  // const image = new Image({
  //   articleImage: req.file.originalname
  // });
  // image
  //   .save()
  //   .then(() => res.json("Ok"))
  //   .catch((error) => console.log(error));
})

module.exports = router;

front form:

import axios from 'axios';
import React, { useState } from 'react';

const NewAdvertisement = () => {
    const [file, setFile] = useState(null);
    file && console.log(file.name);
    const onSubmit = (e) => {
        e.preventDefault();
        const fd = new FormData();
        fd.append("articleImage", file.name);
        console.log("fd", fd);
        axios
            .post("/upload", fd)
            // .then(res => console.log(res))
    }
    return (
        <form
            onSubmit = {onSubmit}
            encType="multipart/form-data"
        >
            <input type = "file" filename="articleImage" onChange = {e => setFile(e.target.files[0])}/>
            <button type = "submit">Submit</button>
        </form>     
    );
};

export default NewAdvertisement;

CodePudding user response:

Replace

<input type = "file" filename="articleImage" ...>

with

<input type = "file" name="articleImage" ...>

CodePudding user response:

it seems you are only posting file.name which is only name of file not binary data. check req.body.articleImage you will get it

  • Related