Skip to content

Instantly share code, notes, and snippets.

Last active April 29, 2021 15:52
Show Gist options
  • Save bingeboy/5589501 to your computer and use it in GitHub Desktop.
Save bingeboy/5589501 to your computer and use it in GitHub Desktop.
Upload and display image with NodeJS and Express.
* Module dependencies.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, common = require('./routes/common')
, fs = require('fs')
, http = require('http')
, util = require('util')
, path = require('path');
var app = express();
* connect middleware - please note not all the following are needed for the specifics of this example but are generally used.
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads' }));
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(__dirname + '/static'));
//File upload
app.get('/upload', common.imageForm);'/upload', common.uploadImage);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
var util = require('util');
exports.imageForm = function(req, res) {
res.render('upload', {
title: 'Upload Images'
exports.uploadImage = function(req, res, next){
console.log('file info: ',req.files.image);
//split the url into an array and then get the last chunk and render it out in the send req.
var pathArray = req.files.image.path.split( '/' );
res.send(util.format(' Task Complete \n uploaded %s (%d Kb) to %s as %s'
, req.files.image.size / 1024 | 0
, req.files.image.path
, req.body.title
, req.files.image
, '<img src="uploads/' + pathArray[(pathArray.length - 1)] + '">'
extends layout
block content
form(action="/upload", method="post", enctype="multipart/form-data")
input(type="text", name="title")
input(type="file", multiple, name="image")
button(type="submit", value="Upload") Upload File
Copy link

Copy link

To access the file property, do this

var getfile = JSON.stringify(files);

This will make it a JSON object.


You will see the file is now accessible and you can use it. To test it, use


Now you can access it, you cannot use it. You have to convert it from a JSON object to a javascript object. Use

var file = JSON.parse(getfiles)

You code is ready to serve you now.

Copy link

I worked in formidable... it might work here

Copy link

Paul-Morris commented Apr 21, 2020

Why does the path to the routes dependency start with ./ but non of the other dependencies have that?
I'm guessing the code is a little dated now? I can't get it to run because when I install routes with npm there are no user or common directories in it:

Error: Cannot find module 'routes/user'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment