Home > database >  File uploading with Express: req.files is undefined
File uploading with Express: req.files is undefined

Time:02-24

I am making a pinterest clone so I need to upload images but I cant fetch files from frontend to back end(with axios) this is the server

I tested so many stuff but I can't understand where is the flaw. The app stores the photo and it seems that the problem happens when I want to get the data to backend but only files cuz I can fetch string from frontend

const express = require('express');
const app = express()
const mongoose = require('mongoose')
const cors = require('cors')
const Photo = require('./models/Photo')
const multer = require('multer')
//MiddleWare
app.use(cors())
app.use(express.json())

mongoose.connect('', () =>{
    console.log('Connected to DB..')
})

// storage 
const Storage = multer.diskStorage({
  destination: 'uploads',
  filename: (req, file,cb) =>{
    cb(null, file.originalname)
  }
})

const upload = multer({
  storage: Storage,
}).single('testImage')

app.post('/add', async(req, res) =>{


  console.log(req.files)
})

app.listen(3001, () =>{
    console.log('Listening..')
})

And this is client side

/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable react/jsx-no-comment-textnodes */
import React, { useState, useRef } from "react";
import NotificationsIcon from "@mui/icons-material/Notifications";
import AddAPhotoIcon from "@mui/icons-material/AddAPhoto";
import "./Header.css";
import axios from "axios"
const Header = ({gallery, setGallery}) => {
  const [open, setOpen] = useState(false);
const [photo, setPhoto] = useState('')
  const handleModel = (e) => {
    setOpen(!open);
  };
  const handlePhoto = (e) => {
    setPhoto(e.target.files[0])
  
}
const handleSubmit = e=>{
  e.preventDefault();
  setOpen(!open);

console.log(photo)
  axios.post('http://localhost:3001/add',{photo: photo})
  .then(res => {
     console.log(res);
  })
  .catch(err => {
     console.log(err);
  });
}
  return (
    <div className="header">
      <div className="nav">
        <img
          src="https://i.pinimg.com/originals/0d/ea/4a/0dea4ad3030467e2f65cde00935ba62b.png"
          className="logo"
        />

        <input type="text" className="search-input" placeholder="Search" />
        <NotificationsIcon color="action" fontSize="large" className="icon" />
        <AddAPhotoIcon
          color="action"
          fontSize="large"
          className="add-icon icon"
          onClick={handleModel}
        />
      </div>
      {open ? (
        <form  onSubmit={handleSubmit} className="popup" encType='multipart/form-data'>
          <input
            type="file"
            accept=".png, .jpg, .jpeg"
            filename='testImage'
            onChange={handlePhoto}

          />
          <button >Submit</button>
        </form>
      ) : (
        ""
      )}
    </div>
  );
};

export default Header;

Server console logs undefined when I upload an image but why tho??

CodePudding user response:

Multer returns you a middleware when you invoke the multer() function.

so in your case you should add the middleware to your route.

const upload = multer({
 storage: Storage,
}).single('testImage');

app.post('/add', upload ,async(req, res) =>{


 console.log(req.file) 
})

Now your route '/add' will look for the key testImage in the multipart/form-data.

CodePudding user response:

You need to pass the upload as formData

const formData = new FormData();
formData.append('files', photo); //this matches req.files

const res = await axios.post('http://localhost:3001/add', formData, {
  headers: formData.getHeaders() //formData will set content-type etc
});

and update route to use middleware

app.post('/add', upload, async(req, res) => {})
  • Related