Last Updated: June 13, 2020
·
3.484K
· frankrousseau

Upload a file from a NodeJS client to an Express server

Original blog post

Client side :

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:

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