uniapp 微信小程序文件操作

下载文件

直接请求文件接口文件打开将会失败,例如xlsx打开将会无法解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
reportApi.getIncome().then(res => {
const fileManagerObj = uni.getFileSystemManager() // 获取全局的文件管理器
console.log(fileManagerObj);
// 文件存储到本地的路径
const filePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.xlsx`
fileManagerObj.writeFile({
data: res, // 拿到的arraybuffer数据
filePath: filePath,
encoding: 'binary',
success: (res) => {
console.log(res) // 成功了的话这里会打印 writeFile:ok
viewDoc(filePath)
}
})
})

使用uniapp提供的downloadFile函数

1
2
3
4
5
6
7
8
9
10
11
12
uni.downloadFile({
url: pjConfig.baseUrl + "/rhhs/reports",
header: {
Authorization: 'Bearer ' + getToken()
},
success: res => {
if (res.statusCode == 200) {
console.log(res)
viewDoc(res.tempFilePath)
}
}
})

打开文件

1
2
3
4
5
6
7
8
9
10
11
function viewDoc(filePath) {
uni.openDocument({
// 直接打开
filePath: filePath, // 这里填上面写入本地的文件路径
fileType: 'xlsx',
showMenu: true, // 右上角是否有可以转发分享的功能,配不配随意
success: (res) => {
console.log('打开文档成功')
}
})
}