It is possible. An example is below.
const http = require('http');
const fs = require('fs');
const filename = "logo.jpg";
const boundary = "MyBoundary12345";
fs.readFile(filename, function (err, content) {
if (err) {
console.log(err);
return
}
let data = "";
data += "--" + boundary + "\r\n";
data += "Content-Disposition: form-data; name=\"file1\"; filename=\"" + filename + "\"\r\nContent-Type: image/jpeg\r\n";
data += "Content-Type:application/octet-stream\r\n\r\n";
const payload = Buffer.concat([
Buffer.from(data, "utf8"),
Buffer.from(content, 'binary'),
Buffer.from("\r\n--" + boundary + "--\r\n", "utf8"),
]);
const options = {
host: "localhost",
port: 8080,
path: "/upload",
method: 'POST',
headers: {
"Content-Type": "multipart/form-data; boundary=" + boundary,
},
}
const chunks = [];
const req = http.request(options, response => {
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => console.log(Buffer.concat(chunks).toString()));
});
req.write(payload)
req.end()
})
The question is interesting. I wonder why it is not already answered (4 years, 9 months).