如何用nodejs通过post发送multipart/form-data类型的http请求
1个回答
2017-06-09 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
参考下:
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);
});
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);
});
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询