1

I am trying to serve images from an "images" file in my project depending on the parameters that the user enters.

For example,

https://localhost:3000/images?fileName=burger

should display the image on the browser

does anyone know how i can go about it?

My structure is as follows:

images ---burger.jpg src ---index.ts

I tried to do it this way but for some reason it won't work

app.use('/images', express.static('images')); 
if(req.query.fileName === "burger"){ res.sendFile("burger.jpg" , {root: path.join("./images")}); } 
1
  • can you share your file structure tree? would help us to understand it better. thank you Commented Nov 3, 2022 at 18:26

1 Answer 1

1

According to your code, if your file structure is following.your code will run perfectly. make sure you set the path to serving static files under express.static() with care and note that your incoming query value exactly matches the file you need to get including the case. this should solve the problem, thank you!

File Structure: images --- burger.jpg index.js 
import express from 'express'; import path from 'path' const app = express(); const PORT = process.env.PORT || 5000; app.use('/images', express.static('images')); app.get('/images', (req, res) => { if(req.query.filename === 'rocket'){ res.sendFile("rocket.jpg" , {root: path.join("./images")}); }) app.listen(PORT, () => { console.log('Server is up and running on PORT: ${PORT}'); }) 

you can also avoid all those fuss by removing that middleware and instead provide absolute path while sending file. for eg:

app.get('/images', (req, res) => { if(req.query.filename === 'rocket'){ res.sendFile(path.join(__dirname, "images/Rocket.jpg")); } }) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.