image-upload.vue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <template>
  2. <view @click="selectAndUpload()">
  3. <slot></slot>
  4. </view>
  5. </template>
  6. <script>
  7. import UNI_APP from '@/.env.js'
  8. export default {
  9. name: "image-upload",
  10. data() {
  11. return {
  12. uploadHeaders: {
  13. "accessToken": uni.getStorageSync('loginInfo').accessToken
  14. }
  15. }
  16. },
  17. props: {
  18. maxCount: {
  19. type: Number,
  20. default: 1
  21. },
  22. maxSize: {
  23. type: Number,
  24. default: 5 * 1024 * 1024
  25. },
  26. sourceType: {
  27. type: String,
  28. default: 'album'
  29. },
  30. isPermanent: {
  31. type: Boolean,
  32. default: false
  33. },
  34. onBefore: {
  35. type: Function,
  36. default: null
  37. },
  38. onSuccess: {
  39. type: Function,
  40. default: null
  41. },
  42. onError: {
  43. type: Function,
  44. default: null
  45. }
  46. },
  47. methods: {
  48. selectAndUpload() {
  49. uni.chooseImage({
  50. count: this.maxCount, //最多可以选择的图片张数,默认9
  51. sourceType: [this.sourceType], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
  52. sizeType: ['original'], //original 原图,compressed 压缩图,默认二者都有
  53. success: (res) => {
  54. res.tempFiles.forEach((file) => {
  55. if (!this.onBefore || this.onBefore(file)) {
  56. // 调用上传图片的接口
  57. this.uploadImage(file);
  58. }
  59. })
  60. }
  61. })
  62. },
  63. uploadImage(file) {
  64. uni.uploadFile({
  65. url: UNI_APP.BASE_URL + '/image/upload?isPermanent=' + this.isPermanent,
  66. header: {
  67. accessToken: uni.getStorageSync("loginInfo").accessToken
  68. },
  69. filePath: file.path, // 要上传文件资源的路径
  70. name: 'file',
  71. success: (res) => {
  72. let data = JSON.parse(res.data);
  73. if (data.code != 200) {
  74. uni.showToast({
  75. icon: "none",
  76. title: data.message,
  77. })
  78. this.onError && this.onError(file, data);
  79. } else {
  80. this.onSuccess && this.onSuccess(file, data);
  81. }
  82. },
  83. fail: (err) => {
  84. console.log(err);
  85. this.onError && this.onError(file, err);
  86. }
  87. })
  88. }
  89. }
  90. }
  91. </script>
  92. <style></style>