Home > Software engineering >  How to serve images as static files using url parameters in express js?
How to serve images as static files using url parameters in express js?

Time:11-04

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")});
}

CodePudding user response:

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"));
    }
})

  • Related