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, "uploads",
image), {
flags : "w+",
encoding : "binary"
});

fd.write(req.body);
fd.end();

fd.on("close", () => {
res.send({ status : "ok", size: len });
});
});

We're expecting an HTTP POST on the /uploads path. It must be an image with a maximum size of 10 MB. Let's analyze the code in detail.

let image = req.params.image.toLowerCase();

if (!image.match(/.(png|jpg)$/)) {
return res.status(403).end();
}

We start by checking whether the image name passed ends with .png or .jpg. If not, we reply with an HTTP 403 response code, which means forbidden, as we're just accepting those types of images:

let len = req.body.length;
let fd = fs.createWriteStream(path.join(__dirname, "uploads", image), {
flags : "w+",
encoding : "binary"
});

We then create a stream to the local file where we'll save our image. The name of the file will be the name of the image. We also store the image size so we can return that to the user when we finish saving. This enables the microservice user to check if we received all the data.

fd.write(req.body);
fd.end();

fd.on("close", () => {
res.send({ status : "ok", size: len });
});

Lastly, we write the image to file and, after properly closing the stream, we reply to the user with a JSON response with a status and a size property.

Don't forget to create the uploads folder inside the microservice folder. Then, restart the service. We'll continue to use curl to test our services. We'll need an image to try it out. I searched for a Google image and saved it locally. I then uploaded it to our service using this command:

curl -X POST -H 'Content-Type: image/png' 
--data-binary @example.png
http://localhost:3000/uploads/example.png

We're telling curl that we want to:

  • Send a POST request
  • Define the Content-Type header saying it's a PNG image
  • Add the content of the example.png file (I downloaded) inside the request body
  • Send the request to the /upload/example.png path of our microservice

After executing the command, I received a JSON response. The size matches my file:

{ "status" : "ok", "size" : 55543 }

We can't see the image using our microservice just yet, but we can check it locally. You should have a copy of the file in the uploads folder. For reference, here's the image I'm using:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset