用node上传临时文件出错,总是返回41001?
在网上找了很多方法尝试了还是不行,完整代码如下: const router = require('express').Router();
const fs = require('fs');
const https = require('https');
const wechatApi = require('./wechatapi');
const { XMLParser, XMLBuilder } = require('fast-xml-parser');
const Jimp = require('jimp');
const FormData = require('form-data');
const axios = require('axios');
let ACCESS_TOKEN = '';
const APP_ID = '*******', APP_SECRET = '*******';
const ACCESS_TOKEN_URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APP_ID}&secret=${APP_SECRET}`;
const WECHAT_UPLOAD_URL = `https://api.weixin.qq.com/cgi-bin/media/upload?`;
router.get('/', (req, res) => {
const checkFlag = wechatApi.checkSignature({ ...req.query });
if(checkFlag){
res.send(req.query.echostr);
}else{
res.send('');
}
});
router.post('/', (req, res) => {
// parse xml to object
const reqObj = new XMLParser().parse(req.body).xml;
var resObj = {
ToUserName: reqObj.FromUserName,
FromUserName: reqObj.ToUserName,
};
switch(reqObj.MsgType){
case 'text':
resObj.MsgType = 'text';
resObj.Content = 'hello, we have received your message';
resObj.CreateTime = Date.now();
res.send(new XMLBuilder().build({
xml: resObj
}));
break;
case 'image':
Jimp.read(reqObj.PicUrl, (err, image) => {
if(err) throw err;
image.gaussian(10)
.getBuffer(Jimp.MIME_JPEG, (err, buffer) => {
fs.writeFile('./image.jpg', buffer, (err) => {
if(err) console.log('write error');
console.log('write successfully');
})
axios.get(ACCESS_TOKEN_URL)
.then((result) => {
console.log('access_token:', result.data.access_token)
ACCESS_TOKEN = result.data.access_token;
const url = `${WECHAT_UPLOAD_URL}access_token=${ACCESS_TOKEN}&type=image`;
const form = new FormData();
form.append('media', buffer, {
filename: 'image',
contentType: 'image/jpeg',
knownLength: buffer.length
});
form.submit(url, (err, formRes) => {
// if(err) return console.log('error');
var data = '';
console.log('submited!');
formRes.on('data', (chunk) => {
data += chunk;
});
formRes.on('end', () => {
console.log(url);
console.log('---', data.toString());
resObj.MsgType = 'image';
resObj.Image = {
MediaId: new XMLParser().parse(data).media_id
}
resObj.CreateTime = Date.now();
console.log(resObj);
res.send(new XMLBuilder().build({
xml: resObj
}));
})
});
})
});
})
break;
}
});
module.exports = router