Created
June 5, 2012 22:23
-
-
Save DanielG/2878504 to your computer and use it in GitHub Desktop.
Node.js HTTP client streaming multipart upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function multipart_upload_stream(url, parts, callback) { | |
| // TODO: better GUID | |
| var boundary = Math.random().toString().slice(2); | |
| var len = 0; | |
| parts = parts.map(function(part){ | |
| part = make_part(part); | |
| len += part.length; | |
| return part; | |
| }); | |
| len += (4 + boundary.length); | |
| var headers = { | |
| 'Content-Type': 'multipart/form-data; boundary=' + boundary, | |
| 'Content-Length': len | |
| }; | |
| var opt = URL.parse(url); | |
| opt.method = 'POST'; | |
| opt.headers = headers; | |
| var req = http.request(opt, function(res){}); | |
| var $end = req.end; | |
| req.end = function(data){ | |
| if(data) req.write(data); | |
| req.write('\r\n--' + boundary + '--'); | |
| $end.call(req); | |
| } | |
| parts.forEach(function(part) { | |
| req.write(part.data); | |
| }); | |
| callback(null, req); | |
| // TODO: filename encoding | |
| function make_part(p){ | |
| var part = '--' + boundary + '\r\n' | |
| + 'Content-Disposition: form-data; name=' + '"' + p.name + '"' | |
| + ( p.filename ? ('; filename=' + '"' + p.filename + '"') : '') | |
| + '\r\n' | |
| + ( p.type ? ('Content-Type:' + p.type + '\r\n') : '' ) | |
| + '\r\n' | |
| + ( p.body ? (p.body + '\r\n') : ''); | |
| part = new Buffer(part); | |
| var len = 0; | |
| if(p.body && p.length) throw "you don't want to do that."; | |
| if(p.length) { | |
| len += p.length + part.length; | |
| } else if(p.body) | |
| len += part.length; | |
| return { | |
| length: len, | |
| data: part, | |
| stream: p.stream | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment