I used multer to download the image and save the path of the image to the database, and then how can I get the image from the client and show it on the screen?
import multer from 'multer';
const storageConfig = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './images')
},
filename: (req, file, cb) => {
cb(null, Date.now() + '-' + file.originalname)
}
})
const upload = multer({storage: storageConfig});
let path = '';
app.post('/upload',upload.single('image'), (req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
if(req.file) {
console.log(req.file);
path = req.file.path;
res.send('hi')
return;
}
res.send('bye')
})
after I received the file path I saved it in the database, but I don’t know how to use it later to show this picture on the screen
2
Answers
As per your code mention, you can show the image in react as below.
In your case backend_url is http://localhost:3000
After saving the path of the file to the database, you need to implement a route to fetch the image url. Then you can simply use it in your client application. Here I’m expecting you are only fetching a single image using the id. If you want to fetch all the urls stored in db, kindly make necessary changes to this code.
Eg:
Server.js
Client (ReactJS)