
In this two part tutorial, we will create a Node.js server which will accept uploading of images. In the second part, we will create an Android app which will upload an image to the Node.js server we created.
In this two part tutorial, we will create a Node.js server which will accept uploading of images. In the second part, we will create an Android app which will upload an image to the Node.js server we created.
Creating the Project
Create a directory named node-image-upload and change to the directory. Create package.json and add the following dependencies.
package.json
{
"name": "node-image-upload",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Raj Amal",
"license": "ISC",
"dependencies": {
"express": "^4.15.3",
"file-type": "^5.2.0",
"multer": "^1.3.0"
}
}
Now type the command npm install to download and install the dependencies.
Creating app.js
We will use the express module to create a server. And multer module is an express middleware which simplifies uploading of files. The file-type module is used to get MIME type of the stored file.
Initially, multer is initialized with destination folder where the images should be stored, the file size of the image and file type. Here we limit the maximum size of the image to 10 MB, and the image type is limited to JPEG.
Next, we will be creating endpoint ‘/images/upload’ with POST method to accept images. We will call the upload() callback method to upload the image. We will send a JSON message with the path of the image to the client on successful upload.
Then we create another endpoint ‘/images/:imagename’ to send the image to the client. We get the image name from the client and read the image from the file system, then send the image as binary.
The express errors are handled using a common express error handler.
app.js
'use strict'
const express = require('express')
const multer = require('multer')
const fileType = require('file-type')
const fs = require('fs')
const app = express()
const router = express.Router()
const port = process.env.PORT || 8080;
const upload = multer({
dest:'images/',
limits: {fileSize: 10000000, files: 1},
fileFilter: (req, file, callback) => {
if (!file.originalname.match(/\.(jpg|jpeg)$/)) {
return callback(new Error('Only Images are allowed !'), false)
}
callback(null, true);
}
}).single('image')
router.post('/images/upload', (req, res) => {
upload(req, res, function (err) {
if (err) {
res.status(400).json({message: err.message})
} else {
let path = `/images/${req.file.filename}`
res.status(200).json({message: 'Image Uploaded Successfully !', path: path})
}
})
})
router.get('/images/:imagename', (req, res) => {
let imagename = req.params.imagename
let imagepath = __dirname + "/images/" + imagename
let image = fs.readFileSync(imagepath)
let mime = fileType(image).mime
res.writeHead(200, {'Content-Type': mime })
res.end(image, 'binary')
})
app.use('/', router)
app.use((err, req, res, next) => {
if (err.code == 'ENOENT') {
res.status(404).json({message: 'Image Not Found !'})
} else {
res.status(500).json({message:err.message})
}
})
app.listen(port)
console.log(`App Runs on ${port}`)
To run the project use the following command,
node app
Testing via Postman
Download Complete Project
You can download the complete project as zip or fork from our Github repository.
In the following part you will learn how to develop Android Application to upload image to this server using Retrofit.