index.vue 2.6 KB

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