upload-file.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. Page({
  2. onShareAppMessage() {
  3. return {
  4. title: '上传文件',
  5. path: 'packageAPI/pages/network/upload-file/upload-file'
  6. }
  7. },
  8. chooseImage() {
  9. const self = this
  10. wx.chooseImage({
  11. count: 1,
  12. sizeType: ['compressed'],
  13. sourceType: ['album'],
  14. success: async function(res) {
  15. const imageSrc = res.tempFilePaths[0]
  16. const r = await wx.cloud.callFunction({
  17. name: 'login',
  18. data: {
  19. action: 'openid'
  20. },
  21. })
  22. const openId = r.result.openid;
  23. const cloudPath = `upload/${openId}.png`
  24. wx.cloud.uploadFile({
  25. cloudPath, // 上传至云端的路径
  26. filePath: imageSrc, // 小程序临时文件路径
  27. config: {
  28. env: 'release-b86096'
  29. },
  30. success: res => {
  31. // 返回文件 ID
  32. console.log(res.fileID)
  33. console.log('uploadImage success, res is:', res)
  34. wx.showToast({
  35. title: '上传成功',
  36. icon: 'success',
  37. duration: 1000
  38. })
  39. self.setData({
  40. imageSrc,
  41. fileID: res.fileID,
  42. })
  43. },
  44. fail({errMsg}) {
  45. console.log('uploadImage fail, errMsg is', errMsg)
  46. }
  47. })
  48. },
  49. fail: res => {
  50. wx.showToast({
  51. icon: 'none',
  52. title: '上传失败',
  53. })
  54. console.log('uploadImage fail, errMsg is', res.errMsg)
  55. }
  56. })
  57. },
  58. onUnload() {
  59. if (this.data.fileID) {
  60. wx.cloud.deleteFile({
  61. fileList: [this.data.fileID]
  62. })
  63. }
  64. },
  65. onLoad() {
  66. this.setData({
  67. theme: wx.getSystemInfoSync().theme || 'light'
  68. })
  69. if (wx.onThemeChange) {
  70. wx.onThemeChange(({theme}) => {
  71. this.setData({theme})
  72. })
  73. }
  74. }
  75. })