Search code examples
javascriptnode.jsreactjsmulter

I'm trying to upload files with multer in node.js backend and react js in frontend but it doesn't work in back side with multer in public folder


frontend with React.js looks good i saw the other people who did same thing as i did but i don't know where is the problem ! anyone can help me ?

    const [cours, setCours] = useState([]);
    const [description, setDescription] = useState("")
    const [title, setTitle] = useState("")
    const coursHandle = (e) => { setCours([e.target.files]) }

    const onsubmit = async (e) => {
       e.preventDefault();

       const formData = new FormData();
       formData.append("description", description);
       formData.append("title", title);
       // cours.forEach((elem) => { formData.append("cours", elem) });
       formData.append("cours", cours)
       // for (let i = 0; i < cours.length; i++) {
       //     formData.append("cours", cours[i])
       // }
       await axios.post("http://localhost:5000/upload", formData)
           .then((res) => console.log("successfully file post", res)).catch((err) => 
            console.log("error with file post", err))
   }

and backend with multer is here this code is in my app.js app.use(express.static(path.join(__dirname, 'public'))); and the public folder is the same place as app.js

const multer = require("multer");
const path = require("path");

const MIME_TYPES = {
    "file/pdf": "pdf",
    "file/docx": "docx",
    "file/txt": "txt",
    "file/png": "png",
    "file/jpeg": "jpg",
    "file/jpg": "jpg",
}

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "public");
    },
    filename: (req, file, cb) => {
        const nameObject = path.parse(file.originalname);
        // const nameObject = file.originalname.split(' ').join('_');
        const extension = MIME_TYPES[file.mimetype];
        cb(null, nameObject.name.split(" ").join("_") + Date.now() + "." + extension);
    }
})

module.exports = { multerUpload: multer({ storage: fileStorage }).single("file") }

Solution

  • I found the answer for my question,

    formData.append("cours", cours)  
    

    Here the key name as i try to send is "cours" and :

    module.exports = { multerUpload: multer({ storage: fileStorage }).single("file") 
    

    Here the key name for single function is "file" !! that was a first problem and another one was this :

    I've forgoten to add this line in my tag !

    encType="multipart/form-data"
    

    And finally my multer js is :

    const fileStorage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, "public/files");
        },
        filename: (req, file, cb) => {
            console.log("filename :", file);
            const nameObject = path.parse(file.originalname);
            cb(null, nameObject.name.split(" ").join("_") + Date.now() + 
         nameObject.ext);
       }
    })
    
    module.exports = { multerUpload: multer({ storage: fileStorage }).array("cours") }