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}")
}

app.post('/', multer({ storage: storage}).single('upload'), (req, res) ->
    console.log(req.file)
    console.log(req.body)
    res.status(204).end()
  )

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 : https://github.com/hidrodixtion/ExampleMultipart

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: