upload-file.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // 参考文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-client-api/storage/uploadFile.html
  2. const app = getApp()
  3. Page({
  4. onShareAppMessage() {
  5. return {
  6. title: '上传文件',
  7. path: 'packageCloud/pages/storage/upload-file/upload-file'
  8. }
  9. },
  10. data: {
  11. theme: 'light',
  12. fileUploaded: false,
  13. fileId: '',
  14. filePath: '',
  15. fromOtherPage: false
  16. },
  17. onLoad(options) {
  18. this.setData({
  19. theme: wx.getSystemInfoSync().theme || 'light'
  20. })
  21. if (wx.onThemeChange) {
  22. wx.onThemeChange(({theme}) => {
  23. this.setData({theme})
  24. })
  25. }
  26. if (options.from) {
  27. this.setData({
  28. fromOtherPage: true
  29. })
  30. }
  31. },
  32. chooseImage() {
  33. const self = this
  34. wx.chooseImage({
  35. count: 1,
  36. sizeType: ['compressed'],
  37. sourceType: ['album'],
  38. success(res) {
  39. console.log('chooseImage success, temp path is', res.tempFilePaths[0])
  40. const filePath = res.tempFilePaths[0]
  41. wx.showLoading({
  42. title: '上传中'
  43. })
  44. app.getUserOpenIdViaCloud()
  45. .then(openid => {
  46. const cloudPath = `upload/${openid}${filePath.match(/\.[^.]+?$/)[0]}`
  47. console.log('cloudPath', cloudPath)
  48. wx.cloud.uploadFile({
  49. cloudPath,
  50. filePath,
  51. success: res => {
  52. console.log('[上传文件] 成功:', res)
  53. app.globalData.fileId = res.fileID
  54. self.setData({
  55. fileUploaded: true,
  56. fileId: res.fileID,
  57. filePath
  58. })
  59. wx.hideLoading()
  60. },
  61. fail: err => {
  62. console.error('[上传文件] 失败:', err)
  63. wx.hideLoading()
  64. wx.showToast({
  65. icon: 'none',
  66. title: '上传失败',
  67. })
  68. }
  69. })
  70. return openid
  71. })
  72. .catch(err => {
  73. console.error(err)
  74. wx.hideLoading()
  75. })
  76. },
  77. fail({errMsg}) {
  78. console.log('chooseImage fail, err is', errMsg)
  79. }
  80. })
  81. }
  82. })