chyoo CHENG
chyoo CHENG

Reputation: 720

How to get the url resource path match in node.js express?

I want to get png image by path like this:

http://127.0.0.1/image/line.png

how do I write the app.get() function to match the path and get the filename, then read the file in location and return it? I am new to express in node.js.

Upvotes: 2

Views: 3292

Answers (1)

Nguyen Sy Thanh Son
Nguyen Sy Thanh Son

Reputation: 5376

If you are using ExpressJS 4.0. You can do it by my example below:

app.get('/image/:fileName', function(req ,res) {
    var path = require('path');
    var file = path.join(PATH_TO_IMAGE_DIRECTORY, req.params.fileName);
    res.sendFile(file);
});

Please make note that you should change PATH_TO_IMAGE_DIRECTORY by your image directory location. For example: __dirname, '../upload'

I shared a full post about upload and get the uploaded images with nodejs and expressjs 4.0: HOW TO UPLOAD FILES WITH NODEJS AND EXPRESSJS 4

Upvotes: 4

Related Questions