upload-file.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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: 'page/cloud/pages/upload-file/upload-file'
  8. }
  9. },
  10. data: {
  11. fileUploaded: false,
  12. fileId: '',
  13. filePath: '',
  14. fromOtherPage: false
  15. },
  16. onLoad(options) {
  17. if (options.from) {
  18. this.setData({
  19. fromOtherPage: true
  20. })
  21. }
  22. },
  23. chooseImage() {
  24. const self = this
  25. wx.chooseImage({
  26. count: 1,
  27. sizeType: ['compressed'],
  28. sourceType: ['album'],
  29. success(res) {
  30. console.log('chooseImage success, temp path is', res.tempFilePaths[0])
  31. const filePath = res.tempFilePaths[0]
  32. wx.showLoading({
  33. title: '上传中'
  34. })
  35. app.getUserOpenIdViaCloud()
  36. .then(openid => {
  37. const cloudPath = 'upload/' + openid + filePath.match(/\.[^.]+?$/)[0]
  38. console.log('cloudPath', cloudPath)
  39. wx.cloud.uploadFile({
  40. cloudPath,
  41. filePath,
  42. success: res => {
  43. console.log('[上传文件] 成功:', res)
  44. app.globalData.fileId = res.fileID
  45. self.setData({
  46. fileUploaded: true,
  47. fileId: res.fileID,
  48. filePath
  49. })
  50. wx.hideLoading()
  51. },
  52. fail: err => {
  53. console.error('[上传文件] 失败:', err)
  54. wx.hideLoading()
  55. wx.showToast({
  56. icon: 'none',
  57. title: '上传失败',
  58. })
  59. }
  60. })
  61. return openid
  62. })
  63. .catch(err => {
  64. console.error(err)
  65. wx.hideLoading()
  66. })
  67. },
  68. fail({errMsg}) {
  69. console.log('chooseImage fail, err is', errMsg)
  70. }
  71. })
  72. }
  73. })