index.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <template>
  2. <view>
  3. <uni-file-picker @select="select" mode="grid" @delete="deletefile" v-model="fileList" :limit="maxSize" file-mediatype="image" :image-styles="imageStyles"></uni-file-picker>
  4. </view>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'MUpload',
  9. data() {
  10. return {
  11. fileList: [],
  12. imageStyles: {
  13. width: 100,
  14. height: 100,
  15. border: {
  16. radius: '5px'
  17. }
  18. }
  19. }
  20. },
  21. props: {
  22. maxSize: {
  23. type: Number,
  24. default: 1
  25. },
  26. value: {
  27. type: Array,
  28. default() {
  29. return []
  30. }
  31. }
  32. },
  33. watch: {
  34. value: {
  35. deep: true,
  36. // immediate: true,
  37. handler: function (newV) {
  38. // 数据为空的三种情况
  39. if (newV === null || newV === '' || newV === undefined) {
  40. this.fileList = []
  41. this.isWatch = true
  42. return
  43. }
  44. // if (this.isWatch) {
  45. // this.isWatch = false
  46. // if (newV.length > 0) {
  47. // #ifndef H5
  48. this.fileList = this.$BaseTool.UserUtil.transImg(newV)
  49. // #endif
  50. // #ifdef H5
  51. this.fileList = newV
  52. // #endif
  53. // } else {
  54. // this.isWatch = true
  55. // }
  56. // }
  57. }
  58. }
  59. },
  60. methods: {
  61. deletefile(e) {
  62. this.fileList = this.fileList.filter(item => item.path !== e.tempFilePath)
  63. this.$emit('input', this.fileList)
  64. this.$emit('change', this.fileList)
  65. },
  66. select(e) {
  67. // 根据所选图片的个数,多次调用上传函数
  68. console.log(e)
  69. let promises = []
  70. for (let i = 0; i < e.tempFilePaths.length; i++) {
  71. const promise = this.uploadFiles(e.tempFilePaths, i)
  72. promises.push(promise)
  73. }
  74. Promise.all(promises).then(() => {})
  75. },
  76. // 上传函数
  77. async uploadFiles(tempFilePaths, i) {
  78. let that = this
  79. await uni.uploadFile({
  80. url: that.$BaseTool.UserUtil.getUploadUrl(),
  81. filePath: tempFilePaths[i],
  82. name: 'file',
  83. header: {
  84. Authorization: that.$BaseTool.UserUtil.getToken(tempFilePaths[0])
  85. },
  86. success: res => {
  87. let data = JSON.parse(res.data) //返回的是字符串,需要转成对象格式
  88. const reg = new RegExp('[;,。!?;,]')
  89. if (reg.test(res.data.fileName)) {
  90. uni.showToast({ icon: 'none', title: '文件名包含非法字符!' })
  91. } else {
  92. that.fileList.push(data.data)
  93. this.$emit('input', this.fileList)
  94. that.$emit('change', that.fileList)
  95. }
  96. },
  97. fail: () => {
  98. uni.showToast({ icon: 'none', title: '上传失败!' })
  99. }
  100. })
  101. }
  102. }
  103. }
  104. </script>
  105. <style>
  106. </style>