Create Simple Image Upload Server in Node.js

  1. Install node & npm
  2. Install express. npm install express
  3. Install multer. npm install multerImage result for nodejs expressjs
  • (Optional) install coffeescript. npm install -g coffee-script
express = require 'express'
multer = require 'multer'
path = require 'path'
crypto = require 'crypto'

app = new express()

storage = multer.diskStorage {
  destination: './uploads'
  filename: (req, file, cb) ->
    crypto.pseudoRandomBytes 16, (err, raw) ->
      return cb(err) if err
      cb(null, "#{raw.toString 'hex'}#{path.extname file.originalname}")
}'/', multer({ storage: storage}).single('upload'), (req, res) ->

app.listen 3000, console.log("Listening on port 3000")

  • storage is used to define where the file will be stored and the file name. Multer didn’t provide file extension, so if you want to, you can get it using path. note: only use this in development / for testing only. Retrieving file extension from its name is bad practice. Never trust file extension given by uploader
  • I’m using crypto library for easier filenaming.
  • Use multer with storage option in post / route
  • single('upload') : when user upload a file (image), we expect the imagehas fieldname upload
  • log the file and multipart body
  • finally, make this app listen at port 3000

Run the server.

You can clone this project here :


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Powered by

Up ↑

%d bloggers like this: