Search code examples
javascriptmulter

How can I patch the multer filename?


const multerStorage = multer.diskStorage({
destination: (req, file, cb) =>{
    cb(null, '../client/public/uploadImg' )
},
filename :  (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix + '_' + file.originalname)
  }

})

Once I careated a unique name for my file and I saved in uploadImg folder now I need to catch the filename so I can fatch on my client side

  {usrs.map((alldata, i)=>(
            <div key={i} >
                <img src={`/uploadImg/${alldata.photo}`} alt="..." />
                <h1> {alldata.name}</h1>
                <h3> {alldata.photo} </h3>
            </div>
        ))}

Solution

  • At some point, your client side is is making an HTTP request (which I assume is an Ajax request) to upload the image.

    That will be handled by some server side code. Here is the example from the documentation:

    const multer  = require('multer')
    const upload = multer({ dest: './public/data/uploads/' })
    app.post('/stats', upload.single('uploaded_file'), function (req, res) {
       // req.file is the name of your file in the form above, here 'uploaded_file'
       // req.body will hold the text fields, if there were any 
       console.log(req.file, req.body)
    });
    

    You need to send the value of req.file (or rather a URL derived from it) in the response to you make to the Ajax request.

    Since your client side code is using JSX, I'm going to assume you are using React.js.

    The client-side code needs to pay attention to that response and store the result in the state.

    You can then read the value from the state when rendering the component.