O'Reilly logo

Hands-On Microservices with Node.js by Diogo Resende

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Downloading images

Now that we have uploaded our file and checked whether it's stored on the server, we want to be able to download it anytime. Let's create a route to download it. It will be just like the HEAD route we created, but now using the GET verb. Here's an example of how we can implement the route:

app.get("/uploads/:image", (req, res) => {    let ext = path.extname(req.params.image);    if (!ext.match(/^\.(png|jpg)$/)) {        return res.status(404).end()    }    let fd = fs.createReadStream(path.join(__dirname, "uploads",     req.params.image));    fd.on("error", (e) => {        if (e.code == "ENOENT") {            return res.status(404).end()        }        res.status(500).end();    });    res.setHeader("Content-Type", "image/" + ext.substr(1));    fd.pipe(res);});

We first start by checking ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required