Steve Bennett Steve Bennett - 2 months ago 6
Node.js Question

Show image with Express, instead of downloading it

A simple server I'm working can serve images. When browsing to the image URL directly, Chrome offers to download the image, rather than just showing it in the browser. Why is that? Presumably it is something in the headers?

The relevant code is this:

tilestore.getTile(req.param("z"), req.param("x"), req.param("y"), function(err, tile) {

if (!err) {
res.send(tile);
} else {
res.send("Tile rendering error: " + err + "\n");
}

});


Do I need to add something to the headers? They are currently as follows:

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 01 Sep 2014 07:22:30 GMT
Content-Type: application/octet-stream
Content-Length: 37779
Connection: keep-alive
X-Powered-By: Express
ETag: W/"9393-1937584155"

Answer

Ok, it's easy. Just set the content-type:

  if (!err) {
    res.contentType('image/png');
    res.send(tile);
  } else {
    res.send("Tile rendering error: " + err + "\n");
  }

These images are always .png.

New headers:

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 01 Sep 2014 07:33:22 GMT
Content-Type: image/png
Content-Length: 37779
Connection: keep-alive
X-Powered-By: Express
ETag: W/"9393-1937584155"
Comments