why my req.files always null while req.body have the file :upload file with express-fileupload/reactjs

1.2k Views Asked by At

i need ur help i can't find the mistake : I m trying to upload a file in my code using express-fileupload but in nodemon the req.files are always null: files: null but I find that my file attribute pass to req.body like : body: { file: '[object File]' } i try testing my URL with RESTer and it's work the file upload but didn t work with my react input i try all the last 4days lot of things but i still didn t find where is my mistake is it in formData?? plaise help me

there is my code for frontend react:

import Message from './Message';
import Progress from './Progress';
import axios from 'axios';

const FileUpload = () => {
  const [file, setFile] = useState('');
  const [filename, setFilename] = useState('Choose File');
  

  const onChange = e => {
      console.log(e.target.files[0].name)
    setFile([e.target.files[0]]);
    setFilename(e.target.files[0].name);
    
  };
 
  const onSubmit = async e => {
    
    const formData = new FormData(); 
    formData.append("file", file);
   
  if(!formData){
   console.log("empty");}
  
  
    try {
        const res = await axios.post('http://localhost:5001/up', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
        
      });
      console.log("file read");
     
      console.log(res)
      const { fileName, filePath } = res.data;
    
    } catch (err) {
     console.log(err)
      
    }
  };

  return (
    <Fragment>
     
      <form onSubmit={onSubmit} enctype='multipart/form-data'>
        <div className='custom-file mb-4'>
          <input
            type='file' 
            enctype='multipart/form-data'
            className='custom-file-input'
            id='customFile'
            onChange={onChange}
          />
          <label className='custom-file-label' htmlFor='customFile'>
            {filename}
          </label>
        </div>

        <input
          type='submit'
          value='Upload'
          className='btn btn-primary btn-block mt-4'
        />
      </form>
     
    </Fragment>
  );
};

export default FileUpload; 

and there is the backend :

import cors from "cors"
import nez_topographie from "./api/controllers/nez_topographie.route.js"
import fileUpload from "express-fileupload"
import multer from "multer"
import bodyParser from "body-parser"
import morgan from "morgan"

const app = express()
app.use(fileUpload({
    createParentPath: true
  }))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan("dev"))




app.use("/nez_topographie", nez_topographie)


app.post('/up', async (req, res) => {
    try {
        console.log(req)
        
        
        if(!req.files) {
            console.log("no")
            res.send({
                status: false,
                message: 'No file uploaded'
            });
        } else {
            //Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
            let avatar = req.files.file;
            
            //Use the mv() method to place the file in upload directory (i.e. "uploads")
            avatar.mv('./' + avatar.name);

            //send response
            res.send({
                status: true,
                message: 'File is uploaded',
                data: {
                    name: avatar.name,
                    mimetype: avatar.mimetype,
                    size: avatar.size
                }
            });
        }
    } catch (err) {
        console.log(err)
        res.status(500).send(err);
    }
});

export default app
2

There are 2 best solutions below

0
On

My solution: Try

    formData.append('file', {
        uri: file[0].uri,
        type: file[0].type,
        name: file[0].fileName
    })

instead of

formData.append("file", file);
1
On

I just ran into this same issue. I had to add a filename to my FormData instance on the front end.

const formData = new FormData(); 
formData.append("file", file, "myfile.txt");

If you want you can also pass the original file name like so

formData.append("file", file, file.name);