image-upload.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. thumbSize: {
  35. type: Number,
  36. default: 50
  37. },
  38. onBefore: {
  39. type: Function,
  40. default: null
  41. },
  42. onSuccess: {
  43. type: Function,
  44. default: null
  45. },
  46. onError: {
  47. type: Function,
  48. default: null
  49. }
  50. },
  51. methods: {
  52. selectAndUpload() {
  53. uni.chooseImage({
  54. count: this.maxCount, //最多可以选择的图片张数,默认9
  55. sourceType: [this.sourceType], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
  56. sizeType: ['original'], //original 原图,compressed 压缩图,默认二者都有
  57. success: (res) => {
  58. res.tempFiles.forEach((file) => {
  59. if (!this.onBefore || this.onBefore(file)) {
  60. // 调用上传图片的接口
  61. this.uploadImage(file);
  62. }
  63. })
  64. }
  65. })
  66. },
  67. uploadImage(file) {
  68. let action = `/image/upload?isPermanent=${this.isPermanent}&thumbSize=${this.thumbSize}`
  69. uni.uploadFile({
  70. url: UNI_APP.BASE_URL + action,
  71. header: {
  72. accessToken: uni.getStorageSync("loginInfo").accessToken
  73. },
  74. filePath: file.path, // 要上传文件资源的路径
  75. name: 'file',
  76. success: (res) => {
  77. let data = JSON.parse(res.data);
  78. if (data.code != 200) {
  79. uni.showToast({
  80. icon: "none",
  81. title: data.message,
  82. })
  83. this.onError && this.onError(file, data);
  84. } else {
  85. this.onSuccess && this.onSuccess(file, data);
  86. }
  87. },
  88. fail: (err) => {
  89. console.log(err);
  90. this.onError && this.onError(file, err);
  91. }
  92. })
  93. }
  94. }
  95. }
  96. </script>
  97. <style></style>