Skip to content

Instantly share code, notes, and snippets.

@xelaz
Forked from richardzcode/imageUpload.js
Created June 5, 2018 10:43
Show Gist options
  • Save xelaz/64e6ee9d5f3a011ae32998972956d34d to your computer and use it in GitHub Desktop.
Save xelaz/64e6ee9d5f3a011ae32998972956d34d to your computer and use it in GitHub Desktop.
Upload image file from Node.js
/**
* 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