image-upload.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. },
  13. props: {
  14. maxCount: {
  15. type: Number,
  16. default: 1
  17. },
  18. maxSize: {
  19. type: Number,
  20. default: 5 * 1024 * 1024
  21. },
  22. sourceType: {
  23. type: String,
  24. default: 'album'
  25. },
  26. isPermanent: {
  27. type: Boolean,
  28. default: false
  29. },
  30. thumbSize: {
  31. type: Number,
  32. default: 50
  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. let action = `/image/upload?isPermanent=${this.isPermanent}&thumbSize=${this.thumbSize}`
  65. uni.uploadFile({
  66. url: UNI_APP.BASE_URL + action,
  67. filePath: file.path, // 要上传文件资源的路径
  68. name: 'file',
  69. success: (res) => {
  70. let data = JSON.parse(res.data);
  71. if (data.code != 200) {
  72. uni.showToast({
  73. icon: "none",
  74. title: data.message,
  75. })
  76. this.onError && this.onError(file, data);
  77. } else {
  78. this.onSuccess && this.onSuccess(file, data);
  79. }
  80. },
  81. fail: (err) => {
  82. console.log(err);
  83. this.onError && this.onError(file, err);
  84. }
  85. })
  86. }
  87. }
  88. }
  89. </script>
  90. <style></style>