Created
August 8, 2012 23:47
-
-
Save richardzcode/3299787 to your computer and use it in GitHub Desktop.
Upload image file from Node.js
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
/** | |
* Example of simulating file upload post form from node.js | |
* | |
* Set your own file and server options. | |
*/ | |
var img = require('fs').readFileSync('./sample.png'); | |
var options = { host: '...' | |
, port: ... | |
, path: ... | |
, method: 'POST' | |
}; | |
var boundary = '--boundary1234567890--' | |
, crlf = '\r\n' | |
, part1 = crlf + 'Content-Type: image/png' | |
+ crlf + 'Content-Disposition: form-data; name="file"; filename="sample.png"' | |
+ crlf + crlf | |
, part2 = img | |
, part3 = crlf + '--' + boundary + '--'; | |
var req = require('http').request(options, function(res) { | |
res.on('end', function() { | |
console.log('Uploaded.'); | |
}); | |
}); | |
req.on('error', function(e) { | |
console.log('Error when upload: ' + e.message); | |
}); | |
req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); | |
req.write(part1, 'utf-8'); | |
req.write(part2, 'binary'); | |
req.write(part3, 'utf-8'); | |
req.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment