uni-app/vue2:微信小程序实现文件流的下载及预览
有时候后端会返回文件流,而不是完整的文件地址。
实现文件流的下载预览方式如下:
// 接口地址
const downloadUrl = base_url + "/service/proBasicService/downloadBillFile"const token = uni.getStorageSync('token');// 参数const obj = {}uni.request({url: downloadUrl, //接口method: 'post',data: obj,responseType: 'arraybuffer',header: {//请求头'X-Access-Token': token},success: res => {console.log('wend', res);if (res.statusCode === 200) {uni.showLoading({title: '下载中...',mask: true})//全局唯一的文件管理器const fs = uni.getFileSystemManager();// 文件名const name = Date.now() + nameconst filePath =`${wx.env.USER_DATA_PATH}/${name}.xlsx`fs.writeFile({//这里填文件的名字filePath: filePath,data: res.data,encoding: "binary",success: (res1) => {console.log('写入文档成功', res1);uni.hideLoading()uni.showToast({title: '文档下载成功',icon: 'none'})uni.openDocument({showMenu: true,filePath: filePath,success: function(res2) {console.log('打开文档成功');},fail: err => {console.log('fail 1', err);}});},fail: err => {uni.hideLoading()uni.showToast({title: '文档下载失败',icon: 'none'})console.log('fail', err);}})}},fail: err => {uni.hideLoading()uni.showToast({title: '文档下载失败',icon: 'none'})}})
有时会出现本地存储文件超过10M的问题,可以尝试清除缓存,如下:
onLoad() {uni.getSavedFileList({success: function(res) {if (res.fileList.length > 0) {// 删除本地存储的文件uni.removeSavedFile({filePath: res.fileList[0].filePath});}}});},
以上即可实现文件流下载