download-file.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const demoImageFileId = require('../../../../config').demoImageFileId
  2. // 参考文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-client-api/storage/downloadFile.html
  3. const app = getApp()
  4. Page({
  5. onShareAppMessage() {
  6. return {
  7. title: '下载文件',
  8. path: 'packageCloud/pages/storage/download-file/download-file'
  9. }
  10. },
  11. data: {
  12. theme: 'light',
  13. fileDownloaded: false,
  14. fileId: '',
  15. filePath: '',
  16. loading: false
  17. },
  18. onLoad() {
  19. this.setData({
  20. theme: wx.getSystemInfoSync().theme || 'light'
  21. })
  22. if (wx.onThemeChange) {
  23. wx.onThemeChange(({theme}) => {
  24. this.setData({theme})
  25. })
  26. }
  27. this.setData({
  28. fileId: app.globalData.fileId || demoImageFileId
  29. })
  30. },
  31. downloadFile() {
  32. const fileId = this.data.fileId
  33. if (!fileId) {
  34. return
  35. }
  36. const self = this
  37. this.setData({
  38. loading: true
  39. })
  40. wx.cloud.downloadFile({
  41. fileID: fileId,
  42. success: res => {
  43. console.log('[下载文件] 成功:', res)
  44. self.setData({
  45. fileDownloaded: true,
  46. filePath: res.tempFilePath
  47. })
  48. },
  49. fail: err => {
  50. console.error('[下载文件] 失败:', err)
  51. },
  52. complete: () => {
  53. self.setData({
  54. loading: false
  55. })
  56. }
  57. })
  58. }
  59. })