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);
}
});
Leonid Beschastny's answer works but I also had to convert ArrayBuffer to Buffer that is used in the Node's
request
module. After uploading file to the server I had it in the same format that comes from the HTML5 FileAPI (I'm using Meteor). Full code below - maybe it will be helpful for others.You can also use the "custom options" support from the request library. This format allows you to create a multi-part form upload, but with a combined entry for both the file and extra form information, like filename or content-type. I have found that some libraries expect to receive file uploads using this format, specifically libraries like multer.
This approach is officially documented in the forms section of the request docs - https://github.com/request/request#forms
An undocumented feature of the
formData
field thatrequest
implements is the ability to pass options to theform-data
module it uses:This is useful if you need to avoid calling
requestObj.form()
but need to upload a buffer as a file. Theform-data
module also acceptscontentType
(the MIME type) andknownLength
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 ofrequest
.Looks like you're already using
request
module.in this case all you need to post
multipart/form-data
is to use itsform
feature:but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:
request
will extract all related metadata by itself.For more information on posting
multipart/form-data
seenode-form-data
module, which is internally used byrequest
.