Skip to content

Instantly share code, notes, and snippets.

@alejandro
Forked from betobaz/app.js
Created December 16, 2011 23:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alejandro/1488596 to your computer and use it in GitHub Desktop.
Save alejandro/1488596 to your computer and use it in GitHub Desktop.
node.js Upload file formidable
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, stylus = require('stylus')
, util = require('util')
//, form = require('connect-form')
, formidable = require('formidable')
, sys = require('sys')
;
var app = module.exports = express.createServer(
);
// Configuration
function compile(str, path){
return stylus(str)
//.import(__dirname + '/public/stylesheets/cruz-azul')
.set('filename', path)
.set('warn', true)
.set('compress', true);
};
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public', compile: compile }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
//console.log('hola, esto trae sucursalprovider:', SucursalProvider);
// Routes
app.get('/upload-file', function(req, res){
res.send(
'<form action="/upload-file" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
res.end();
});
app.post('/upload-file', function(req, res, next){
var form = new formidable.IncomingForm(),
fields = [],files=[];
form.uploadDir = './uploads';
form
.on('error', function(err){
res.writeHead(200, {'content-type':'text/plain'});
res.end('error:\n\n'+util.inspect(err));
})
.on('field', function(field, value){
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function(){
console.log('-> post done');
res.writeHead('200', {'content-type':'text/plain'});
res.end('received fields:\n\n'+util.inspect(fields) +'\n\n received files: ' + util.inspect(files));
});
console.log(req);
form.parse(req);
});
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
@betobaz
Copy link

betobaz commented Dec 17, 2011

Sigue sin poderme cargar el documento, no entiendo por que, solo pego este codigo y no funciona, a continuación la peticion

connection:
{ bufferSize: 0,
fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher: [Object],
destroyed: false,
readable: true,
_writeQueue: [],
_writeQueueEncoding: [],
_writeQueueFD: [],
_writeQueueCallbacks: [],
_writeWatcher: [Object],
writable: true,
_writeImpl: [Function],
_readImpl: [Function],
_shutdownImpl: [Function],
remoteAddress: '127.0.0.1',
remotePort: 55886,
server: [Object],
ondrain: [Function],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: Sat, 17 Dec 2011 05:19:51 GMT,
_events: [Object],
ondata: [Function],
onend: [Function],
_httpMessage: [Circular] },
_events: { finish: [Function] },
_headers: { 'x-powered-by': 'Express' },
_headerNames: { 'x-powered-by': 'X-Powered-By' },
app:
{ stack: [Object],
connections: 1,
allowHalfOpen: true,
watcher: [Object],
_events: [Object],
httpAllowHalfOpen: false,
cache: {},
settings: [Object],
redirects: {},
isCallbacks: {},
_locals: [Object],
dynamicViewHelpers: {},
errorHandlers: [],
route: '/',
routes: [Object],
router: [Getter],
__usedRouter: true,
type: 'tcp4',
fd: 5 },
req: [Circular] },
next: [Function: next],
body: { title: 'Main Menu' },
_events:
{ error: [Function],
aborted: [Function],
data: [Function],
end: [Function] },
files:
{ upload:
{ size: 14401,
path: '/tmp/89efde57cc6c71cf62e7c3aaeed8ef1c',
name: 'betobaz_avatar.png',
type: 'image/png',
lastModifiedDate: Sat, 17 Dec 2011 05:19:51 GMT,
_writeStream: [Object],
length: [Getter],
filename: [Getter],
mime: [Getter] } },
originalMethod: 'POST',
_route_index: 0,
route:
{ path: '/upload-file',
method: 'post',
callbacks: [ [Function] ],
keys: [],
regexp: /^/upload-file/?$/i,
params: [] },
params: [] }
{ socket:
{ bufferSize: 0,
fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher:
{ socket: [Circular],
callback: [Function: onReadable] },
destroyed: false,
readable: true,
_writeQueue: [],
_writeQueueEncoding: [],
_writeQueueFD: [],
_writeQueueCallbacks: [],
_writeWatcher:
{ socket: [Circular],
callback: [Function: onWritable] },
writable: true,
_writeImpl: [Function],
_readImpl: [Function],
_shutdownImpl: [Function],
remoteAddress: '127.0.0.1',
remotePort: 51928,
server:
{ stack: [Object],
connections: 1,
allowHalfOpen: true,
watcher: [Object],
_events: [Object],
httpAllowHalfOpen: false,
cache: {},
settings: [Object],
redirects: {},
isCallbacks: {},
_locals: [Object],
dynamicViewHelpers: {},
errorHandlers: [],
route: '/',
routes: [Object],
router: [Getter],
__usedRouter: true,
type: 'tcp4',
fd: 5 },
ondrain: [Function],
_idleTimeout: 120000,
_idleNext:
{ repeat: 120,
_idleNext: [Circular],
_idlePrev: [Circular],
callback: [Function] },
_idlePrev:
{ repeat: 120,
_idleNext: [Circular],
_idlePrev: [Circular],
callback: [Function] },
_idleStart: Sat, 17 Dec 2011 05:21:51 GMT,
_events:
{ timeout: [Function],
error: [Function],
close: [Function] },
ondata: [Function],
onend: [Function],
_httpMessage:
{ output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
_hasBody: true,
_trailer: '',
finished: false,
socket: [Circular],
connection: [Circular],
_events: [Object],
_headers: [Object],
_headerNames: [Object],
app: [Object],
req: [Circular] } },
connection:
{ bufferSize: 0,
fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher:
{ socket: [Circular],
callback: [Function: onReadable] },
destroyed: false,
readable: true,
_writeQueue: [],
_writeQueueEncoding: [],
_writeQueueFD: [],
_writeQueueCallbacks: [],
_writeWatcher:
{ socket: [Circular],
callback: [Function: onWritable] },
writable: true,
_writeImpl: [Function],
_readImpl: [Function],
_shutdownImpl: [Function],
remoteAddress: '127.0.0.1',
remotePort: 51928,
server:
{ stack: [Object],
connections: 1,
allowHalfOpen: true,
watcher: [Object],
_events: [Object],
httpAllowHalfOpen: false,
cache: {},
settings: [Object],
redirects: {},
isCallbacks: {},
_locals: [Object],
dynamicViewHelpers: {},
errorHandlers: [],
route: '/',
routes: [Object],
router: [Getter],
__usedRouter: true,
type: 'tcp4',
fd: 5 },
ondrain: [Function],
_idleTimeout: 120000,
_idleNext:
{ repeat: 120,
_idleNext: [Circular],
_idlePrev: [Circular],
callback: [Function] },
_idlePrev:
{ repeat: 120,
_idleNext: [Circular],
_idlePrev: [Circular],
callback: [Function] },
_idleStart: Sat, 17 Dec 2011 05:21:51 GMT,
_events:
{ timeout: [Function],
error: [Function],
close: [Function] },
ondata: [Function],
onend: [Function],
_httpMessage:
{ output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
_hasBody: true,
_trailer: '',
finished: false,
socket: [Circular],
connection: [Circular],
_events: [Object],
headers: [Object],
headerNames: [Object],
app: [Object],
req: [Circular] } },
httpVersion: '1.1',
complete: true,
headers:
{ host: 'localhost:3000',
connection: 'keep-alive',
referer: 'http://localhost:3000/upload-file',
'content-length': '14695',
'cache-control': 'max-age=0',
origin: 'http://localhost:3000',
'user-agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryqroS9I9ylWip0klB',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,
/
;q=0.8',
'accept-encoding': 'gzip,deflate,sdch',
'accept-language': 'es-ES,es;q=0.8',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
cookie: 'csrftoken=57d3a0eee61a849459475705a263649e' },
trailers: {},
readable: false,
url: '/upload-file',
method: 'POST',
statusCode: null,
client:
{ bufferSize: 0,
fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher:
{ socket: [Circular],
callback: [Function: onReadable] },
destroyed: false,
readable: true,
_writeQueue: [],
_writeQueueEncoding: [],
_writeQueueFD: [],
_writeQueueCallbacks: [],
_writeWatcher:
{ socket: [Circular],
callback: [Function: onWritable] },
writable: true,
_writeImpl: [Function],
_readImpl: [Function],
_shutdownImpl: [Function],
remoteAddress: '127.0.0.1',
remotePort: 51928,
server:
{ stack: [Object],
connections: 1,
allowHalfOpen: true,
watcher: [Object],
_events: [Object],
httpAllowHalfOpen: false,
cache: {},
settings: [Object],
redirects: {},
isCallbacks: {},
_locals: [Object],
dynamicViewHelpers: {},
errorHandlers: [],
route: '/',
routes: [Object],
router: [Getter],
__usedRouter: true,
type: 'tcp4',
fd: 5 },
ondrain: [Function],
_idleTimeout: 120000,
_idleNext:
{ repeat: 120,
_idleNext: [Circular],
_idlePrev: [Circular],
callback: [Function] },
_idlePrev:
{ repeat: 120,
_idleNext: [Circular],
_idlePrev: [Circular],
callback: [Function] },
_idleStart: Sat, 17 Dec 2011 05:21:51 GMT,
_events:
{ timeout: [Function],
error: [Function],
close: [Function] },
ondata: [Function],
onend: [Function],
_httpMessage:
{ output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
_hasBody: true,
_trailer: '',
finished: false,
socket: [Circular],
connection: [Circular],
_events: [Object],
_headers: [Object],
_headerNames: [Object],
app: [Object],
req: [Circular] } },
httpVersionMajor: 1,
httpVersionMinor: 1,
upgrade: false,
originalUrl: '/upload-file',
query: {},
app:
{ stack:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
connections: 1,
allowHalfOpen: true,
watcher: { host: [Circular], callback: [Function] },
_events:
{ request: [Function],
connection: [Function: connectionListener],
listening: [Function] },
httpAllowHalfOpen: false,
cache: {},
settings:
{ env: 'development',
hints: true,
views: '/home/betobaz/Documentos/programacion/nodejs/express_example/views',
'view engine': 'jade' },
redirects: {},
isCallbacks: {},
_locals: { settings: [Object], app: [Circular] },
dynamicViewHelpers: {},
errorHandlers: [],
route: '/',
routes:
{ app: [Circular],
routes: [Object],
params: {},
_params: [],
middleware: [Function] },
router: [Getter],
__usedRouter: true,
type: 'tcp4',
fd: 5 },
res:
{ output: [],
outputEncodings: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
_hasBody: true,
_trailer: '',
finished: false,
socket:
{ bufferSize: 0,
fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher: [Object],
destroyed: false,
readable: true,
_writeQueue: [],
_writeQueueEncoding: [],
_writeQueueFD: [],
_writeQueueCallbacks: [],
_writeWatcher: [Object],
writable: true,
_writeImpl: [Function],
_readImpl: [Function],
_shutdownImpl: [Function],
remoteAddress: '127.0.0.1',
remotePort: 51928,
server: [Object],
ondrain: [Function],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: Sat, 17 Dec 2011 05:21:51 GMT,
_events: [Object],
ondata: [Function],
onend: [Function],
_httpMessage: [Circular] },
connection:
{ bufferSize: 0,
fd: 7,
type: 'tcp4',
allowHalfOpen: true,
_readWatcher: [Object],
destroyed: false,
readable: true,
_writeQueue: [],
_writeQueueEncoding: [],
_writeQueueFD: [],
_writeQueueCallbacks: [],
_writeWatcher: [Object],
writable: true,
_writeImpl: [Function],
_readImpl: [Function],
_shutdownImpl: [Function],
remoteAddress: '127.0.0.1',
remotePort: 51928,
server: [Object],
ondrain: [Function],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: Sat, 17 Dec 2011 05:21:51 GMT,
_events: [Object],
ondata: [Function],
onend: [Function],
_httpMessage: [Circular] },
_events: { finish: [Function] },
_headers: { 'x-powered-by': 'Express' },
_headerNames: { 'x-powered-by': 'X-Powered-By' },
app:
{ stack: [Object],
connections: 1,
allowHalfOpen: true,
watcher: [Object],
_events: [Object],
httpAllowHalfOpen: false,
cache: {},
settings: [Object],
redirects: {},
isCallbacks: {},
_locals: [Object],
dynamicViewHelpers: {},
errorHandlers: [],
route: '/',
routes: [Object],
router: [Getter],
__usedRouter: true,
type: 'tcp4',
fd: 5 },
req: [Circular] },
next: [Function: next],
body: { title: 'Main Menu' },
_events:
{ error: [Function],
aborted: [Function],
data: [Function],
end: [Function] },
files:
{ upload:
{ size: 14401,
path: '/tmp/120ba36bbeb5e3a285c158a00a193bda',
name: 'betobaz_avatar.png',
type: 'image/png',
lastModifiedDate: Sat, 17 Dec 2011 05:21:51 GMT,
_writeStream: [Object],
length: [Getter],
filename: [Getter],
mime: [Getter] } },
originalMethod: 'POST',
_route_index: 0,
route:
{ path: '/upload-file',
method: 'post',
callbacks: [ [Function] ],
keys: [],
regexp: /^/upload-file/?$/i,
params: [] },
params: [] }

@alejandro
Copy link
Author

Según miro, este es todo el objeto req o request o como sea que lo estés haciendo. SI lo esta subiendo, nada más que al directorio que formidable tiene por default osea :: /tmp/:FILENAME como te decía no estas pasando apropiadamente el parámetro del directorio donde se va a subir el archivo. Hace esto en la consola y dime que ves: cd /tmp | ls ahí deben de aparecer los archivos, nada más que con un nombre distinto al original algo como 120ba36bbeb5e3a285c158a00a193bda.

@betobaz
Copy link

betobaz commented Dec 17, 2011 via email

@betobaz
Copy link

betobaz commented Dec 19, 2011

Si aparecen todos en /tmp, ya le asigno el directorio form.uploadDir = './uploads';, pero los sigue colocando en tmp. Imprimo las opciones del formidable.IncomingForm() y si trae la cadena que le indico. Pero al imprimir el objeto upload del request efectivamente me indica que el archivo lo subio al directorio tmp, quiero suponer que primero lo coloca en tmp y despues lo mueve al directorio que se le indica.

@alejandro
Copy link
Author

No no actua de esa forma, lo sube directamente a la carpeta especificada, lo único que se me viene a la mente es que no existe el directorio uploads o que no tienes permisos para escribir en la carpeta, trata de hacer sudo chown -R $USER ./uploads dentro del directorio del server (para asignarte propietario del directorio), luego imprimi la cadena form: console.log(form) justo luego de haber definido el form.uploadDir y debe de imprimir algo como esto:

{ error: null,
  ended: false,
  maxFieldsSize: 2097152,
  keepExtensions: false,
  uploadDir: './uploads',
  encoding: 'utf-8',
  headers: null,
  type: null,
  bytesReceived: null,
  bytesExpected: null,
  _parser: null,
  _flushing: 0,
  _fieldsSize: 0 }

Ahí podes ver si realmente te esta pasando el parámetro.

@betobaz
Copy link

betobaz commented Dec 19, 2011

Ya encontre por que, en la linea 31, se configura app.use(express.bodyParser());, si comento esta linea ya funciona, ahora a buscar el por que!, Gracias por tu ayuda.

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