Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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") }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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") } 
about 4 years ago · Juan Pablo Isaza Relatório

0

In last line

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

the argument under single is file, but in your frontend form there is no input with name file maybe you have to change the argument of single function from file to cours

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda