效果图 功能---导出表格存储至手机
实现步骤:通过后端返回的字节流 -- wx.downloadFile() -- wx.getFileSystemManager() -- wx.openDocument()
exportFun() { //点击导出
let token = wx.getStorageSync('token');
let that = this
wx.request({
url: commonTool.baseUrl + "mall/myShop/export/" + app.globalData.userInfo.id,
data: {
seachStr: that.data.params // 筛选导出
},
header: {
"content-type": "application/json",
"token": token
},
dataType: "json",
success: res => {
// 返回的 res.data.msg 是一个名称eg: xxxx.xlxs
if (res.data.code == 0) {
that.download(res.data.msg)
}
}
})
},
// 查看导出返回的字节流
download(fileName) {
let token = wx.getStorageSync('token');
wx.downloadFile({ // downloadFile的url必须为http或者https
url: commonTool.baseUrl + "mall/myShop/common/download?delete=true&fileName=" + fileName,
header: {
"content-type": "application/json",
"token": token
},
responseType: "arraybuffer", //注意这里的responseType
success(res) {
console.log('downloadfile', res)
const manage = wx.getFileSystemManager();
if (res.statusCode === 200) {
manage.saveFile({
tempFilePath: res.tempFilePath,
filePath: wx.env.USER_DATA_PATH + "/待派单明细.xlsx", // 文件重命名 可自定义
success: function(res) {
}
});
// 打开文档
wx.openDocument({
filePath: wx.env.USER_DATA_PATH + "/待派单明细.xlsx",
success: function(res) {
console.log('打开文档成功')
},
fail: function() {
console.log('打开失败');
}
})
}
},
fail(err) {
console.log('downloadfile err', err)
}
})
}
这样就实现啦! 下面是我实现时踩过得坑 导出函数不变,download函数内容不同。思路是:获取字节流 -- writeFile() -- wx.openDocument() 这个思路只能在微信开发者工具pc端上实现,在真机上压根不执行wx.downloadFile并且会报错"protocol"
// 查看导出返回的字节流
download(fileName) {
let token = wx.getStorageSync('token');
wx.request({
url: commonTool.baseUrl + "mall/myShop/common/download?delete=true&fileName=" + fileName,
header: {
"content-type": "application/json",
"token": token
},
responseType: "arraybuffer", //注意这里的responseType
success: res => {
console.log('获取字节流', res);
var fileManager = wx.getFileSystemManager();
var FilePath = wx.env.USER_DATA_PATH + "/" + fileName;
fileManager.writeFile({
data: res.data,
filePath: FilePath,
encoding: "binary", //编码方式
success: result => {
console.log('FilePath',FilePath) // FilePath为 wxfile://***
wx.downloadFile({
url: FilePath, // download的url必须为http或https链接
header: {
"content-type": "application/json",
"token": token
},
success(res) {
// 打开文档
wx.openDocument({ //我这里成功之后直接打开
filePath: res.tempFilePath,
fileType: "xlsx",
success: result => {
console.log('打开文件', result);
},
fail: result => {
console.log(result);
}
});
},
fail: res => {
console.log(res);
}
})
}
})
}
希望能对正在浏览的你有些许的帮助~程序猿盆友们加油吖!