Search code examples
node.jsmulter

Multer not able to get the filename


I'm not able to get the filename or path from Multer. This is what I've done so far:

uploadcsv.js

 const fileUpload = multer({
    limits: 500000,
    storage:multer.diskStorage({
        destination: (req, file, cb) =>{
            cb(null,'upload/csv')
        },
        filename: (req, file, cb) =>{
            const ext = MIME_TYPE_MAP[file.mimetype]
            cb(null, uuid + '.' + ext)
        },
        fileFilter: (req, file, cb) =>{
            const isValid = !!MIME_TYPE_MAP[file.mimetype]
            let error = isValid ? null : new Error('Invalid mime type')
            cb(error, isValid)
        }
    })
})

Then the route api:

 router.post('/contact/importcontact', JWTAuthenticationToken, fileUpload.single('csv'), async (req, res) => {
      console.log(req.body)
      console.log(req.file.filename)
      const csvFilePath = req.file.filename
      const stream = fs.createReadStream(csvfile);
    
      const account= await Account.findOne({ acctid: { "$eq": req.body.acctid } })
    
      try {
        if (req.file == undefined)
          return res.status(400).send({ msg: 'No files were uploaded.' });
    
          csvtojson()
          .fromFile(csvFilePath)
          .then((jsonObj) => {
            console.log(jsonObj);
          })
    
        // Async / await usage
        const jsonArray = await csvtojson().fromFile(csvFilePath);
    
    
    res.json({ success: "Uploaded Successfully", status: 200 })
      } catch (error) {
      res.json({ message: error })
    }
    })

Lastly, the react importcustomer.js

 const handleCSVChange = (e) => {
        console.log(e.target.files[0])
        setCsvData(e.target.files[0])
        setUploadButtonData(e.target.files[0].name)
    }


    const uploadCSVData = async (e) => {     
        setLoading(true)
        const formData = new FormData();       
        formData.append("csv", csvData);
        console.log(formData)
        e.preventDefault()
        const response = await Axios.post(process.env.REACT_APP_FETCH_URL + '/api/contact/importcontact', { formData: formData, acctid: lsData.acctid}, { withCredentials: true })
        if (response.data.statusCode === "409") {
            setMessage(response.data.msg)
            setLoading(false)
        }
        else if (response.data.statusCode === "200") {
            setLoading(false)
            //history.push('/sources')
        }
    }

    return (
        <div className="col-12 grid-margin stretch-card">
        <div className="card">
            <div className="card-body">
                <h4 className="card-title">Import Customer Data From CSV</h4>               
                <form className="forms-sample" enctype="multipart/form-data">
                    <div className="form-group">
                        <label for="files" className="btn btn-primary">{uploadButtonData}
                            <input id="files" type="file" name="csv" className="form-control" hidden accept="*.csv" onChange={handleCSVChange} /></label>
                    </div>
                    <button className="btn btn-primary" onClick={uploadCSVData} style={{ float: "right", width: "7rem" }} type="button">
                        {loading && <i className="fa fa-refresh fa-spin"></i>}
                            Upload CSV</button>
                    <div className="mt-3" style={{ textAlign: "center" }}>
                        <span id="msg" style={{ color: "red" }}>{message}</span>
                    </div>
                </form>
            </div>
        </div>
    </div>
    )

Though I'm able to console.log(req.body) and console.log(e.target.files[0]) and getting the acctid and filename but returned empty for the console.log(formData) and console.log(req.file.filename) returned undefined. What have I missed? Many thanks in advance and greatly appreciate any helps. Thanks again


Solution

  • I have managed to solves this by appending the acctid to formData:

     const formData = new FormData();       
           formData.append("csv", csvData);
           formData.append("accctid", lsData.acctid);
    
    const response = await Axios.post(process.env.REACT_APP_FETCH_URL + '/api/contact/importcontact', formData, { withCredentials: true })