Upload a file from a NodeJS client to an Express server

I didn’t find any simple resource about how to upload files from a Node.js app to a Node.js Express server. They all give solutions based on NodeJS native API or old Express API. That’s fine but using the right libraries will make your life easier.

So here are two littlle snippets that give you the way to easily handle file uploads with Request-json and Express. If you want to understand what happens under the hood, read the following documentations/codes : request-json, request, form-data, express, body parser, multipart middleware, formidable.

Client side :

# client.coffee
Client = require("request-json").JsonClient
client = new Client "http://localhost:3000/"

extradata = tag: "happy"
client.sendFile 'file-upload/', './test.png', extradata, (err, res, body) ->
    if err then console.log err else console.log 'file uploaded'

Server side:

# server.coffee
express = require 'express'
fs = require 'fs'
app = express()

# File uploading requires express body parser.
app.use express.bodyParser
    keepExtensions: true # optional
    uploadDir: '/my/path/upload/files'

app.post '/file-upload', (req, res) ->
    file = req.files.file

    # Express middleware gives a temporary name to the file, so we rename it.
    fs.rename file.path, "/my/path/upload/files/#{file.name}", (err) ->
        res.send error: err if err
        console.log "file uploaded. Extradata: tag = #{req.body.tag}"
        res.send success: true

6 Responses to Upload a file from a NodeJS client to an Express server

  1. Adrian Verne says:

    “Oh great an Express file upload tutorial…”

    Coffeescript.

    *close tab*

  2. rieshellin says:

    Oh! great….

  3. Denis Vuyka says:

    Please add “CoffeeScript” to the header of the article, so that people don’t waste time opening it.

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

%d bloggers like this: