weixin.js代码
else if(content==='5'){ var data=yield wechatApi.uploadMaterial('image',__dirname+'/2.jpg') reply={ type:'image', mediaId:data.media_id, } console.log(reply);
tpl.js代码
<% } else if(msgType==='image'){ %> <Image> <MediaId><![CDATA[<%= content.mediaId %>]]></MediaId> </Image> <% } else if(msgType==='voice'){ %>
wechat.代码
Wechat.prototype.uploadMaterial = function(type,filepath){ var that=this; var form={//构造一个表单 media : fs.createReadStream(filepath) } return new Promise(function(resolve,reject){//Promise 实例 that .fetchAccessToken() .then(function(data){ var url=api.upload+'access_token='+data.access_token+'&type='+type; request({method:'POST',url:url,formData:form,json:true}) .then(function(response){//请求, var _data=response.body;//response[1] if(_data){ resolve(_data) }else{ throw new Error('Upload material fails') } }) .catch(function(err){ reject(err); }) }) }) }
控制台输出