请问如何用nodejs通过post发送multipart/form-data类型的http请求?
发布于 13 年前 作者 xuhaijinsky2008 106522 次预览 最后一次回复是 7 年前 来自
请问如果用nodejs通过post发送multipart/form-data类型的http请求?
网络上搜索的都是解析multipart/form-data表单的,express已经提供了较好的支持,那NODEJS如果后台模拟发送multipart/form-data类型消息呢?上传个图片给接口方。
比如如何在后台用https.request模拟类似请求?纠结几天了,请大侠帮帮忙哦。
<form name='sendMsgToWxByPost' action='https://api.com/media?access_token=AAA' method="post" enctype="multipart/form-data" >
<input type=“file” name=“media” /> </form>
我知道application/x-www-form-urlencoded类型的请求是这样模拟的。
var post_data = querystring.stringify({
type : "text",
content: content
});
//1、创建消息
var options = {
host: 'api.com',
port: 443,
path: '/messages?access_token='+accessToken,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var reqHttps = https.request(options, function(resHttps) {
console.log("statusCode: ", resHttps.statusCode);
console.log("headers: ", resHttps.headers);
resHttps.setEncoding('utf8');
resHttps.on('data', function(body1) {
console.log("body:"+body1);
}
// write data to request body
reqHttps.write(post_data);
reqHttps.end();
reqHttps.on('error', function(e) {
console.error("error:"+e);
return "系统异常:"+e.message;
});13 回复
post_data 照着这里的格式发就行了: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
我本来想在往微博发图片的功能里用的,不过做到一半改用了另一个通过地址上传图片的接口。
发个半成品的代码给你参考下:
最后面
console.log(body)中 body 里的数据就是要发送的数据看了一下,确实能够方便的满足此类需求,相见恨晚啊
嗯。昨天我也按照这样思路写的,模拟发post。发现Content-Length的计算结果和直接在IE浏览器提交抓包得到的数据差四个字符,很是诧异,不过总算可以上传给接口方了。是参考的这三篇文章,分享下啊: enter link description here enter link description here enter link description here
@xuhaijinsky2008 http://stackoverflow.com/questions/9943010/node-js-post-file-to-server http://stackoverflow.com/questions/5744990/how-to-upload-a-file-from-node-js http://yefeng.iteye.com/blog/315847 重新贴下链接
我也试试哈
@saighost 学习了,但是我的是个图片,没中文,呵呵,不过防止以后有中文,还是用那种方式吧,呵呵。
自己写的方法可以跑了,贴出来。
//发送单条消息给接口方 app.post("/sendMsgToAByPost",function(req, res, next) {
});
不明觉厉!
学习了,收藏。
@xiongliding 你好,我现在就是在开发微博接口的时间需要用这种方式,但是我还是没有明白,微博接口要的是一个二进制图片,这里需要怎么处理?
@uznu 二进制你把图片读取为流就行了,参考9楼