simpleUpload.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <template>
  2. <u-upload :disabled="readonly" :fileList="uplodFiles" @afterRead="afterRead" @delete="deletePic" name="1" multiple
  3. :maxCount="maxCount"></u-upload>
  4. </template>
  5. <script>
  6. import {
  7. getCache
  8. } from '@/utils/cache';
  9. import { uploadUrl } from '@/api/system';
  10. export default {
  11. name: "simpleUpload",
  12. props: {
  13. action: {
  14. type: String,
  15. required: false,
  16. default: uploadUrl,
  17. },
  18. headers: {
  19. type: Array,
  20. required: false,
  21. default: () => []
  22. },
  23. postData: {
  24. type: Object,
  25. required: false,
  26. default: () => ({})
  27. },
  28. fileList: {
  29. type: Array,
  30. required: false,
  31. default: () => [],
  32. },
  33. maxCount: {
  34. type: Number,
  35. required: false,
  36. default: 10,
  37. },
  38. readonly: {
  39. type: Boolean,
  40. required: false,
  41. default: false,
  42. }
  43. },
  44. data() {
  45. return {
  46. uplodFiles: this.fileList
  47. };
  48. },
  49. watch: {
  50. fileList(n, o) {
  51. this.uplodFiles = n
  52. }
  53. },
  54. methods: {
  55. async afterRead(event) {
  56. const tokenData = await getCache('token')
  57. const token = tokenData.data
  58. console.log('upload', event, this.uplodFiles, this.fileList);
  59. let lists = [].concat(event.file)
  60. lists.forEach(item => {
  61. this.uplodFiles.push({
  62. ... item,
  63. status: 'uploading',
  64. message: '上传中'
  65. })
  66. })
  67. for(let i = 0 ; i < this.uplodFiles.length; i ++) {
  68. const item = this.uplodFiles[i]
  69. if(item.status && item.status === 'uploading') {
  70. const res = await this.doUpload(item.url, token)
  71. const resData = JSON.parse(res.data)
  72. console.log(res);
  73. item.status = 'success'
  74. item.url = resData.data
  75. this.$set(this.uplodFiles, i, {
  76. ... item
  77. })
  78. }
  79. }
  80. this.$emit('on-change', this.uplodFiles)
  81. },
  82. deletePic(event) {
  83. const url = event.file.url
  84. this.uplodFiles = this.uplodFiles.filter(d => d.url !== url)
  85. this.$emit('on-change', this.uplodFiles)
  86. },
  87. async doUpload(filePath, token) {
  88. return new Promise((resolve, reject) => {
  89. uni.uploadFile({
  90. url: this.action,
  91. filePath: filePath,
  92. header: {
  93. token,
  94. },
  95. success: (res) => {
  96. resolve(res)
  97. },
  98. fail: (err) => {
  99. reject(err)
  100. }
  101. })
  102. })
  103. }
  104. }
  105. }
  106. </script>
  107. <style>
  108. </style>