expressjs / multer

Node.js middleware for handling `multipart/form-data`.
MIT License
11.58k stars 1.06k forks source link

react not show me images in front end I am using multer in express js but un able watch my images in front end #1141

Open hassni12 opened 2 years ago

hassni12 commented 2 years ago

Frontend

const uploadImageHandler = async (e) => { const file = e.target.files[0] console.log(file,"file") const formData = new FormData()

    formData.append('image', file)
   console.log(formData,"formDataFile")
    try {

        const config = {
            header: { 'content-type': 'multipart/form-data' }
        }
        const { data } = await axios.post('http://localhost:8000/api/upload', formData, config)
        setImage(data)
        console.log(data.name, "axios image")
    } catch (error) {
        console.log(error)

    }
}

backend

onst router = express.Router(); const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, './upload')

},
filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${(file.originalname)}`)
}

}) function checkFileType(file,cb){ const fileType=/jpg|jpeg|png/ const extname=fileType.test(path.extname(file.originalname).toLowerCase()) console.log(extname ,"extname") const mimetype=fileType.test(file.mimetype) if (extname&&mimetype){ return cb(null, true)

}else{
    cd('image only !')
}

} const upload=multer({ storage, fileFilter:function(req,file, cb){ checkFileType(file,cb)

}

}) router.post('/',upload.single('image'),(req,res)=>{ // console.log(req.file.path) const url = req.protocol + '://' + req.get('host') // console.log(+req.file.path); res.send(/${req.file.path}) })

router.post('/multiupload',upload.array('image', 3),(req,res)=>{ console.log(req.files) res.send(req.files.path) })

export default router;

app.use('/upload',express.static(__dirname+'/upload'));

UnKnoWn-Consortium commented 2 years ago

So are the images uploaded saved and present at the backend or not? If yes, muller is working as intended.