1

Once i open 'localhost:3000' , the image is getting downloaded to my laptop instead of being displayed on the webpage , can anyone please help me out ?

var express= require('express');
var fs = require('fs');
var app= express();

var imgpath= 'C:\Users\Rohit\Downloads\images.jpg';

app.get('/',function(req,res){
  res.send(fs.readFileSync(imgpath));
});

app.listen(3000);
console.log('listening');
2
  • You need to pass the image url to a view, so use res.render('<view_file>'); and in that view write <img src = "path"> to display on webpage. Commented Jun 7, 2016 at 3:46
  • can you explain why res.send wont work here , in the way it works for strings or json items ? Commented Jun 7, 2016 at 3:59

2 Answers 2

4

You have to set header.

app.get('/',function(req,res){
  res.set('Content-Type', 'image/jpg');//Added line
  res.send(fs.readFileSync(imgpath));
});
Sign up to request clarification or add additional context in comments.

6 Comments

i'm new to all this sir , can you explain why do we have to set header ?
By default browser expect content-type: text/html. Browser try to identify by extension of url if it is image or pdf. It can not be identified by extension then browser download the file.
but in the url - .jpg was mentioned , why couldn't it identify it as an image ?
by setting header img/jpg we recommend browser to handle it as image.
I have checked localhost:3000/abc.jpg by changing the code that as well downloading the image if we don't pass the header.
|
0

you must set content-type

res.type('jpg').send(fs.readFileSync(imgpath));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.