如何用nodejs通过post发送multipart/form-data类型的http请求
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用nodejs通过post发送multipart/form-data类型的http请求相关的知识,希望对你有一定的参考价值。
参考技术A 参考下:var https = require('https');
var fs = require('fs');
var util = require('util');
var path = require('path');
var BOUNDARYPREFIX = 'nbglme';
var mkpic = function (pic, fn)
var mimes =
'.png': 'image/png',
'.gif': 'image/gif',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg'
;
var ext = path.extname(pic);
var mime = mimes[ext];
if (!mime) return;
fs.readFile('/home/bnlt/'+pic, function (err, data)
content = util.format('Content-Disposition: form-data; name="pic"; filename="%s"\r\n', pic);
content += util.format('Content-Type: %s\r\n\r\n', mime);
content += data;
fn(content);
);
var mkfield = function (field, value)
return util.format('Content-Disposition: form-data; name="%s"\r\n\r\n%s', field, value);
exports.post = function (param, onsuccess, onfailer)
if (param.pic)
mkpic(param.pic, function (pic)
var data = [pic];
delete param.pic;
for (var i in param)
data.push(mkfield(i, param[i]));
var max = 9007199254740992;
var dec = Math.random() * max;
var hex = dec.toString(36);
var boundary = BOUNDARYPREFIX + hex;
var body = util.format('Content-Type: multipart/form-data; boundary=%s\r\n\r\n', boundary)
+ util.format('--%s\r\n', boundary)
+ data.join(util.format('\r\n--%s\r\n', boundary))
+ util.format('\r\n--%s', boundary);
console.log(body);
);
最后面 console.log(body) 中 body 里的数据就是要发送的数据 参考技术B
用request模块,通过设置formData发送。关于formData,具体如何用看这里:
本回答被提问者采纳https://github.com/form-data/form-data
https://www.npmjs.com/package/request
以上是关于如何用nodejs通过post发送multipart/form-data类型的http请求的主要内容,如果未能解决你的问题,请参考以下文章