文档中心>实践教程>腾讯云微搭低代码>小程序中实现文件下载

小程序中实现文件下载

最近更新时间:2024-12-16 17:49:41

我的收藏

背景

excel、pdf、word 等类型文件在小程序中并不能直接保存到手机本地,需要调用小程序相关 API,以生成在线预览文件的形式实现转发保存。本篇实践主要介绍如何在小程序场景中实现文件从下载到保存的步骤。

操作步骤

1. 场景搭建,新建 javascript 方法 function1 实现文件下载,按钮点击事件绑定该方法。



其中 function1 方法代码如下:
export default function ({ event, data }) {
wx.cloud.downloadFile({
fileID: 'cloud://lowcode-0ghsfkoo8e3f415d.6c6f-lowcode-xxxxxxxxx-1258057692/weda-uploader/_香港人口密度_导入模版-20241125112431.xlsx',
success: res => {
console.log(res)
if (res.statusCode == 200) {
console.log(res.statusCode)
wx.getFileSystemManager().saveFile({
tempFilePath: res.tempFilePath,
success: function (res) {
// 保存文件成功
console.log(res.savedFilePath)
wx.openDocument({
filePath: res.savedFilePath,
showMenu: true,
})
},
fail: function (error) {
// 保存文件失败
console.log(error)
}
})
}

},
fail: err => {
// handle error
}
})

}
相关小程序 API 说明:
wx.cloud.downloadFile:从云存储空间下载文件,其中参数 fileID 为对应云文件 ID。



wx.getFileSystemManager().saveFile:保存文件到小程序域,是一个相对隐式的地址,文件类型为 wxfile 。
wx.openDocument:以新页面打开文档,用户可单击页面右上角,手动保存或转发文件。
2. 发布小程序应用,在真机环境下查看,可以看到下载文件,成功生成本地 wxfile 文件后自动跳转到文件预览页面,单击预览页右上角即可将文件进行转发分享。