I have problem uploading file using POST request in Node.js. I have to use request
module to accomplish that (no external npms). Server needs it to be multipart request with the file
field containing file's data. What seems to be easy it's pretty hard to do in Node.js without using any external module.
I've tried using this example but without success:
request.post({ uri: url, method: 'POST', multipart: [{ body: '<FILE_DATA>' }] }, function (err, resp, body) { if (err) { console.log('Error!'); } else { console.log('URL: ' + body); } });
You can send the file as a FormData (multipart/form-data) if you need to send more fields or as a Blob if you just want to send the binary directly.
var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.
Looks like you're already using request
module.
in this case all you need to post multipart/form-data
is to use its form
feature:
var req = request.post(url, function (err, resp, body) { if (err) { console.log('Error!'); } else { console.log('URL: ' + body); } }); var form = req.form(); form.append('file', '<FILE_DATA>', { filename: 'myfile.txt', contentType: 'text/plain' });
but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:
form.append('file', fs.createReadStream(filepath));
request
will extract all related metadata by itself.
For more information on posting multipart/form-data
see node-form-data
module, which is internally used by request
.
An undocumented feature of the formData
field that request
implements is the ability to pass options to the form-data
module it uses:
request({ url: 'http://example.com', method: 'POST', formData: { 'regularField': 'someValue', 'regularFile': someFileStream, 'customBufferFile': { value: fileBufferData, options: { filename: 'myfile.bin' } } } }, handleResponse);
This is useful if you need to avoid calling requestObj.form()
but need to upload a buffer as a file. The form-data
module also accepts contentType
(the MIME type) and knownLength
options.
This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0
or above of request
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With