26

Node.js, Express.js and Multer Restful API for Image Uploader

 5 years ago
source link: https://www.tuicool.com/articles/hit/FJjQRjR
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A short step by step tutorial on Restful API for Image Uploader using Node.js, Express.js, and Multer. We are using the form `multipart/form-data` `enctype` for upload image using RESTful API. To make it simple we are using Multer Node.js library/module. Now, we will show you how to use it from scratch.

Tableof Contents:

  • Create New Express.js Application and Required Modules
  • Implementing Image Upload in RESTful API Route
  • Run and Test the Node.js, Express.js and Multer Image Uploader

The following tools, frameworks, and modules are required for this tutorial:

  • Node.js
  • Express.js
  • Multer
  • Terminal or Command Line
  • Text Editor or IDE
  • Postman

We assume that you have to install Node.js in your machine and can run `node`, `npm` or `yarn` command in your terminal or command line. Next, check their version by type this commands in your terminal or command line.

node -v
v10.15.1
npm -v
6.8.0
yarn -v
1.10.1

That the versions that we are uses. Let's continue with the main steps.

1. Create New Express.js Application and Required Modules

Open your terminal or node command line the go to your projects folder. First, install express generator using this command.

sudo npm install express-generator -g

Next, create an Express.js app using this command.

express image-uploader

Next, go to the newly created project folder then install node modules.

cd image-uploader && npm install

There's no view yet using the latest Express generator. We don't need it because we will create a RESTful API. Next, install modules for uploading an image.

npm install --save multer

Now, you are ready to create RESTful API for image upload.

2. Implementing Image Upload in RESTful API Route

We will an existing route for image upload endpoint. Open and edit `app.js` then change this line.

app.use('/', index);

To this line.

app.use('/api/', indexRouter);

Next, open and edit `routes/index.js` then add this required variables.

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, './public/images');
    },
    filename: (req, file, cb) => {
      console.log(file);
      var filetype = '';
      if(file.mimetype === 'image/gif') {
        filetype = 'gif';
      }
      if(file.mimetype === 'image/png') {
        filetype = 'png';
      }
      if(file.mimetype === 'image/jpeg') {
        filetype = 'jpg';
      }
      cb(null, 'image-' + Date.now() + '.' + filetype);
    }
});
var upload = multer({storage: storage});

As you can see, we are saving the image file in `public/images` folder and give a name to the image file as `image-date`. If there's no images folder exists, create one inside the public folder. Next, create a new route for image upload.

router.post('/upload',upload.single('file'),function(req, res, next) {
  console.log(req.file);
  if(!req.file) {
    res.status(500);
    return next(err);
  }
  res.json({ fileUrl: 'http://192.168.0.7:3000/images/' + req.file.filename });
})

That RESTful API sends a response of Image file URL that accessible to Express.js web server.

3. Run and Test the Node.js, Express.js and Multer Image Uploader

To test this Express.js application, just run this command.

nodemon

or

npm start

Next, open the Postman application then change the method to `POST` and the URL to `http://localhost:3000/api/upload`. Change the body to `form-data` then fill the key as file and pick an image file. You can see the Postman request as below.

3ArERrB.png!web

You will see this response for a successful upload.

{
    "fileUrl": "http://192.168.0.7:3000/images/image-1553473134646.png"
}

Now, you can check the uploaded image by entering that address from the API response.

That it's, our simple tutorial of creating Image Uploader using Node.js, Express.js, and Multer. You can get the full source code from our GitHub .

That just the basic. If you need more deep learning about MEAN Stack, Angular, and Node.js, you can take the following cheap course:

Thanks!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK