diff --git a/lib/multipartform.js b/lib/multipartform.js index 7196724..a744532 100644 --- a/lib/multipartform.js +++ b/lib/multipartform.js @@ -101,42 +101,49 @@ Part.prototype = { // with the whole Part // Calls the callback when complete write: function(stream, callback) { - - var self = this; - - //first write the Content-Disposition - stream.write(this.header()); - - //Now write out the body of the Part - if (this.value instanceof File) { - fs.open(this.value.path, "r", 0666, function (err, fd) { - if (err) throw err; - - var position = 0; - - (function reader () { - fs.read(fd, 1024 * 4, position, "binary", function (er, chunk) { - if (er) callback(err); - stream.write(chunk); - position += 1024 * 4; - if (chunk) reader(); - else { - stream.write("\r\n") - callback(); - fs.close(fd); - } - }); - })(); // reader() - }); - } else if (this.value instanceof Data) { - stream.write(this.value.data); - stream.write("\r\n"); - callback(); - } else { - stream.write(this.value + "\r\n"); - callback(); - } - } + + var self = this; + + //first write the Content-Disposition + stream.write(this.header()); + + //Now write out the body of the Part + if (this.value instanceof File) { + fs.open(this.value.path, 'r+', function (err, fd) { + var stats = fs.fstatSync(fd); + var bufferSize = stats.size + if (err) throw err; + var chunkSize = 512; + var position = 0; + var buf = new Buffer(bufferSize); + (function reader () { + + if ((position + chunkSize) > bufferSize) { + chunkSize = (bufferSize - position); + } + + fs.read(fd, buf, position, chunkSize, position, function (er, chunk, buf) { + if (er) callback(err); + stream.write(buf.slice(position, chunkSize + position)); + position += chunkSize; + if (position < bufferSize) reader(); + else { + stream.write("\r\n") + callback(); + fs.close(fd); + } + }); + })(); // reader() + }); + } else if (this.value instanceof Data) { + stream.write(this.value.data); + stream.write("\r\n"); + callback(); + } else { + stream.write(this.value + "\r\n"); + callback(); + } + } } //Renamed to MultiPartRequest from Request