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

Uploading images

Let's first add our route to handle uploading images. We'll use a body parser module that will handle compressed requests automatically for us.

npm install body-parser --save

We'll include it along with other core modules that we'll need. Add these lines on the top of our service file:

const bodyparser = require("body-parser");const path       = require("path");const fs         = require("fs");

We can now create the function that will handle our upload:

app.post("/uploads/:image", bodyparser.raw({    limit : "10mb",    type  : "image/*"}), (req, res) => {    let image = req.params.image.toLowerCase();    if (!image.match(/\.(png|jpg)$/)) {        return res.status(403).end();    }    let len = req.body.length; let fd = fs.createWriteStream(path.join(__dirname, ...

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