11module . exports = handler
22
33var Busboy = require ( 'busboy' )
4- var each = require ( 'async' ) . each
54var debug = require ( 'debug' ) ( 'ldnode:post' )
65var header = require ( '../header' )
76var patch = require ( './patch' )
@@ -10,7 +9,7 @@ var error = require('../http-error')
109function handler ( req , res , next ) {
1110 var ldp = req . app . locals . ldp
1211 var contentType = req . get ( 'content-type' )
13-
12+ debug ( 'content-type is ' , contentType )
1413 // Handle SPARQL(-update?) query
1514 if ( contentType === 'application/sparql' ||
1615 contentType === 'application/sparql-update' ) {
@@ -37,7 +36,7 @@ function handler (req, res, next) {
3736 }
3837
3938 // Dispatch to the right handler
40- if ( contentType === 'multipart/form-data' ) {
39+ if ( req . is ( 'multipart/form-data' ) ) {
4140 multi ( req , res , next )
4241 } else {
4342 one ( req , res , next )
@@ -46,30 +45,34 @@ function handler (req, res, next) {
4645
4746 function multi ( ) {
4847 debug ( 'receving multiple files' )
49- var busboy = new Busboy ( { headers : req . headers } )
50- var files = [ ]
5148
49+ var busboy = new Busboy ( { headers : req . headers } )
5250 busboy . on ( 'file' , function ( fieldname , file , filename , encoding , mimetype ) {
5351 debug ( 'one file received via multipart: ' + filename )
54- files . push ( { stream : file , name : filename } )
52+ ldp . post (
53+ req . hostname ,
54+ containerPath ,
55+ filename ,
56+ file ,
57+ false ,
58+ function ( err ) {
59+ if ( err ) {
60+ busboy . emit ( 'error' , err )
61+ }
62+ } )
5563 } )
64+ busboy . on ( 'error' , function ( err ) {
65+ debug ( 'error receiving the file: ' + err . message )
66+ next ( error ( 500 , 'Error receiving the file' ) )
67+ } )
68+
69+ // Handled by backpressure of streams!
5670 busboy . on ( 'finish' , function ( ) {
57- each (
58- files ,
59- function ( file , callback ) {
60- ldp . post (
61- req . hostname ,
62- containerPath ,
63- file . filename ,
64- file . stream ,
65- false ,
66- callback )
67- } , function ( err ) {
68- debug ( 'done storing files' + ( err ? 'with error' + err . message : 'with no error' ) )
69- res . sendStatus ( err ? 500 : 200 )
70- next ( )
71- } )
71+ debug ( 'done storing files' )
72+ res . sendStatus ( 200 )
73+ next ( )
7274 } )
75+ req . pipe ( busboy )
7376 }
7477
7578 function one ( ) {
@@ -85,6 +88,7 @@ function handler (req, res, next) {
8588 if ( err ) {
8689 return next ( err )
8790 }
91+ debug ( 'file stored on ' + resourcePath )
8892 header . addLinks ( res , linkHeader )
8993 res . set ( 'Location' , resourcePath )
9094 res . sendStatus ( 201 )
0 commit comments