未分类 · 2024年5月22日 0

微信图床之浏览器直传

将微信公众号素材库当作图床使用

第一步服务端获取公众号的access_token

async getWechatServiceAccountAccessToken(appid: string, appsecret: string) {
  let accessToken = await this.cacheManager.get(`${appid}_access_token`);
  if (accessToken) {
    return accessToken;
  }
  let res = await axios.get(
    `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`
  );
  console.log(res.data);
  // noinspection SpellCheckingInspection
  if (res.data['errcode']) {
    // noinspection SpellCheckingInspection
    throw new Error(res.data['errmsg']);
  } else {
    await this.cacheManager.set(
      `${appid}_access_token`,
      res.data['access_token'],
      {
        ttl: 7000,
      }
    );
    return res.data['access_token'];
  }
}

第二部 浏览器端直接传

HTML

<el-upload
  action="#"
  :http-request="uploadHandler"
  :drag="true"
  :name="'media'"
  :show-file-list="false"
>
  <el-icon><plus /></el-icon>
  <template #tip>
   <div class="el-upload__tip">只能上传jpg/png文件,且不超过10MB</div>
  </template>
</el-upload>

JS

const uploadActionUrl = computed(() => {
  return `/wechat-api/cgi-bin/material/add_material?access_token=${wechatAccessToken.value}&type=image`;
});
let wechatAccessToken = ref("");
async function uploadHandler({ file }: UploadRequestOptions) {
  console.log(file);
  const formData = new FormData();
  formData.append("media", file, file.name);
  let res = await axios.post(uploadActionUrl.value, formData, {});
  console.log(res);
}

上传截图

image.png

image.png

下面这个就是微信素材库的图

这个就是微信素材库的图