refactor: update mpFileUpload (#524)

This commit is contained in:
Honwhy Wang 2025-01-23 06:39:37 +08:00 committed by GitHub
parent 48e96440cc
commit c9b7213863
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -344,37 +344,37 @@ async function mpFileUpload(file: File) {
const { appID, appsecret, proxyOrigin } = JSON.parse(
localStorage.getItem(`mpConfig`)!,
)
/* eslint-disable no-async-promise-executor */
return new Promise<string>(async (resolve, reject) => {
try {
const access_token = await getMpToken(appID, appsecret, proxyOrigin).catch(e => console.error(e))
const access_token = await getMpToken(appID, appsecret, proxyOrigin)
if (!access_token) {
reject(new Error(`获取 access_token 失败请检查console日志`))
return
throw new Error(`获取 access_token 失败`)
}
const formdata = new FormData()
formdata.append(`media`, file, file.name)
const requestOptions = {
method: `POST`,
data: formdata,
}
let url = `https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${access_token}&type=image`
if (proxyOrigin) {
url = `${proxyOrigin}/cgi-bin/material/add_material?access_token=${access_token}&type=image`
}
const res = await fetch<any, {
url: string
}>(url, requestOptions)
const res = await fetch<any, { url: string }>(url, requestOptions)
if (!res.url) {
throw new Error(`上传失败未获取到URL`)
}
let imageUrl = res.url
if (proxyOrigin && window.location.href.startsWith(`http`)) {
imageUrl = `https://wsrv.nl?url=${encodeURIComponent(imageUrl)}`
}
resolve(imageUrl)
}
catch (e) {
reject(e)
}
})
return imageUrl
}
// -----------------------------------------------------------------------