Skip to content

Instantly share code, notes, and snippets.

@bingeboy
Last active Apr 29, 2021
Embed
What would you like to do?
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.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads' }));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(__dirname + '/static'));
app.use(express.errorHandler());
});
//File upload
app.get('/upload', common.imageForm);
app.post('/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.name
, 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
@Paul-Morris
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