Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS POST multipart/form-data request

I want to send files from Node JS through http module using multipart/form-data content-type. The problem with binary encoding. It's OK when I'm trying to send simple text file:

url: 'some-site.com',
method: 'POST',
headers: 
{
    'content-type': 'multipart/form-data; boundary=-----BNDRY',
    'content-length': 128
},
body: '-------BNDRY\r\ncontent-type: text/plain\r\ncontent-disposition: form-data; name="file"; filename="file.txt"\r\n\r\ntest\r\n-------BNDRY--'
}

But when I'm trying to send something like JPG after file reading (e.g. via FS modile) and translate Buffer to string for request body it fails. I've tried different combinations of Buffer.toString(encoding) method and content-transfer-encoding: encoding header but there was no success. For some reason, base64 encoding doesn't work too, I've tested it with connect bodyParser, and seems like it doesn't care about content-transfer-encoding: base64 header in body - content still comes as undecoded base64 string.

And I don't want to use external modules like node-formidable or express to solve my problem.

Thanks.

like image 840
Wayne Avatar asked Feb 23 '26 18:02

Wayne


1 Answers

You simply can save the Buffer to file without encoding:

fs.writeFile(fileBuffer)

OR you can use a package like this to completely handle the scenario: Use this package: https://www.npmjs.com/package/multi-part-form-data-upload

USAGE :

// Express
const uploader = require('multi-part-form-data-upload')(options /* config options */ );
const app = express();

app.post('/uploads',uploader, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ body: req.body }));
});

//  OR Http

const http = require('http');
const uploader = require('multi-part-form-data-upload')(options /* config options */ );

const server = http.createServer(async (req, res) => {
  if (req.url === '/uploads' && req.method.toLowerCase() === 'post') {
    await uploader(req, res, () => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ body: req.body }));
    });
    return;
  }
}
like image 174
Harpal Singh Avatar answered Feb 25 '26 12:02

Harpal Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!