axios 上传文件到微信公众号接口提示503错误

const FormD=require('form-data')
const axios=require('axios')
const form=new FormD()
const config = { headers: { 'Content-Type': 'multipart/form-data' } }
form.append('media',fs.createReadStream(path.join(__dirname, '/test.jpg')))
let resp=await axios
.post(`https://api.weixin.qq.com/cgi-bin/material/add_material?type=image&access_token=${accessToken}`,form,config)
// resp 返回 503错误

使用request则成功上传

const form = { // 构造表单
        media: fs.createReadStream(path.join(__dirname, '/test.png'))
      }
let opt = {
        url: `https://api.weixin.qq.com/cgi-bin/material/add_material?type=image&access_token=${accessToken}`,
        method: 'POST',
        formData: form,
        json: true
      }
let rest = await rp(opt)

请问axios对于formData的处理与request有什么不同?
微信开发文档中

media 是 form-data中媒体文件标识,有filename、filelength、content-type等信息

有对于media的定义,axios在处理form-data的时候是否会缺少某些字段属性?

阅读 5.3k
2 个回答
新手上路,请多包涵

可以用request-promise库。
代码类似:

const accessToken = await wxUtil.getMPAccessToken();
const url = `https://api.weixin.qq.com/wxa/img_sec_check?access_token=${accessToken}`;

var options = {
    method: 'POST',
    uri:url,
    formData: {
        name: 'media',
        file: {
            value: fs.createReadStream(file.path),
            options: {
                filename: 'test.jpg',
                contentType: 'image/jpg'
            }
        }
    }
};

const result = await rp(options)
    .then(function (body) {
        return body;
    })
    .catch(function (err) {
        return err;
    });

fs.unlinkSync(file.path);

ctx.body = JSON.parse(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题