Now we have our server, however this is something very basic and not enough for our needs, so we will add dependencies in order to reach our goal: routing and uploading files

Part 2 : Express

First, you must create 2 folders at the root of the project:

$ mkdir upload api

First, you must create 2 folders at the root of the project: The 1st will store the images while the second will manage the interface with the user: the API

Then we install the dependencies:

$ npm install express multer --save

We save the dependencies in the package.json so that someone who takes over the project can quickly install these dependencies. Express will handle routing while multer takes care of uploading images


//content of api/app.js
const express = require('express')
const multer = require('multer')

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}.${file.mimetype.split('/')[1]}`)
  }
})

const upload = multer({ storage })

const app = express()

app.post('/photos/upload', upload.array('photos'), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
  // TODO: photos handling
})

module.exports = app

Explanations:

We have created a route, which on the url / photos / upload downloads and stores the images sent to it. The form field (the ‘name’) should be named photos. We will also change index.js a bit to integrate the API in the application, we export our module “app” to import it into the main file:


//content of index.js
const http = require('http')
const port = 3000
const app = require('./api/app')

const server = http.createServer(app)

// bind the server on port
server.listen(port, (err) => {
    if (err) {
        return console.log('something bad happened', err)
    }
    console.log(`server is listening on ${port}`)
})

You will find the code here.

In the next article we will take care to communicate with the Clarifay API to get the photos tags.