index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import api from '@/api'
  2. // 上传头像mixin
  3. export const avatarMixin = {
  4. data () {
  5. return {
  6. cropperOption: {
  7. visible: false,
  8. img: null
  9. }
  10. }
  11. },
  12. methods: {
  13. uploadImg (event) {
  14. let file = event.target.files[0]
  15. if (this.beforeAvatarUpload(file)) {
  16. this.readFileAsBlob(file)
  17. }
  18. },
  19. readFileAsBlob (file) {
  20. let self = this
  21. let reader = new FileReader()
  22. reader.readAsDataURL(file)
  23. reader.onload = e => {
  24. self.cropperOption.img = e.target.result
  25. self.cropperOption.visible = true
  26. }
  27. reader.onerror = () => {
  28. self.readFileAsBlob(file)
  29. }
  30. },
  31. cropperClose () {
  32. this.cropperOption.visible = false
  33. },
  34. cropperSubmit (image) {
  35. let param = new FormData()
  36. param.append('user_id', this.$store.state.userId)
  37. param.append('token', this.$store.state.token)
  38. param.append('cover_photo', image)
  39. if (this.isMe) {
  40. api.user.changePhoto(param).then(({ data }) => {
  41. if (data.code === 0) {
  42. this.handleAvatarSuccess(image)
  43. this.cropperClose()
  44. }
  45. })
  46. } else {
  47. param.append('group_id', this.$store.state.curSession)
  48. api.group.changeCover(param).then(({ data }) => {
  49. if (data.code === 0) {
  50. this.handleAvatarSuccess(image)
  51. this.cropperClose()
  52. }
  53. })
  54. }
  55. },
  56. handleAvatarSuccess (file) {
  57. let imageUrl = URL.createObjectURL(file)
  58. this.$showTips(this.$t('public.uploadSucc'))
  59. if (this.isMe) {
  60. // 用户头像
  61. this.$store.commit('updateUserPhoto', imageUrl)
  62. this.$store.commit('updateMemberInfo', {
  63. userId: this.$store.state.userId,
  64. imageUrl: imageUrl
  65. })
  66. } else {
  67. // 群头像
  68. this.$store.dispatch('updateSessionItem', {
  69. sessionId: this.$store.state.curSession,
  70. data: {
  71. cover_photo: imageUrl
  72. }
  73. })
  74. this.$store.commit('updateGroup', {
  75. key: 'coverPhoto',
  76. data: imageUrl
  77. })
  78. }
  79. },
  80. beforeAvatarUpload (file) {
  81. const isIMG = file.type.indexOf('image') > -1
  82. const isLt1M = file.size / 1024 / 1024 < 2
  83. if (!isIMG || !isLt1M) {
  84. this.$showTips(this.$t('userinfo.maxUploadTips'))
  85. }
  86. return isIMG && isLt1M
  87. }
  88. }
  89. }