接口返回blob,如何实现小程序下载
小程序中嵌入H5,如何实现文件流的下载
处理接口参数:
const userInfo = LocalCache.getSession("userInfo"); const orgType = LocalCache.getSession("orgType"); const { orgCode, accessToken, appToken } = userInfo || {}; const token = LocalCache.getCache("token"); const origin = window.location.origin; const params = { startTime: data.startTime, endTime: data.endTime, gradeIds: data.gradeIds?.join(",") || "", orgCode: userInfo.orgCode, }; const currentUrl = encodeURIComponent(window.location.href); const paramsObj = `token=${token}&accessToken=${accessToken}&appToken=${appToken} &appKey=${appKey}&orgType=${orgType}`;currentUrl 是下载之后需要返回的页面url
paramsObj 是接口请求头的参数,如鉴权需要的参数
处理下载接口需要用到的参数
const query = new URLSearchParams({ startTime: params.startTime, endTime: params.endTime, gradeIds: params.gradeIds, orgCode: params.orgCode, token, accessToken, appToken, appKey, orgType, source: orgType === "11" ? "pre" : "general", }); const url = `${origin}/xgk/opengateway/preschool/api/v1/interaction/export/sta?${query.toString()}`;url 是下载接口的路径,将参数拼接到后面
转码处理
如果url太长需要进行编码处理,fileName、currentUrl等参数过场也需要编码处理
const fileUrl = encodeURIComponent(url); let allUrl = `/modules/fileCode/pages/handleFile/index?isDownload=1&fileName=班级统计表.xlsx¤tUrl=${currentUrl}&fileUrl=${fileUrl}`; console.log("allUrl", allUrl); wx.miniProgram.navigateTo({ url: allUrl, });/modules/fileCode/pages/handleFile/index 此处为固定路径,后面的参数根据下载文件的内容进行修改
项目里面引入微信api
import wx from "weixin-js-sdk";