fileUpload.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <template>
  2. <el-upload
  3. class="upload-demo"
  4. action="#"
  5. :http-request="handlRequest"
  6. :before-remove="beforeRemove"
  7. :on-remove="handleRemove"
  8. multiple
  9. :before-upload="beforeUpload"
  10. :file-list="fileList"
  11. >
  12. <slot>
  13. <el-button size="small" type="primary">点击上传</el-button>
  14. </slot>
  15. </el-upload>
  16. </template>
  17. <script>
  18. import { uploadFile, removeFile } from '@/api/system/file/index.js';
  19. import { getImageUrl, getImagePath } from '@/utils/file';
  20. export default {
  21. props: {
  22. value: {
  23. type: Array,
  24. default: () => []
  25. },
  26. // 所属模块
  27. module: {
  28. type: String,
  29. required: true
  30. },
  31. // 限制数量
  32. limit: {
  33. type: Number,
  34. default: -1
  35. },
  36. // 限制大小 mb
  37. size: {
  38. type: Number,
  39. default: 10
  40. }
  41. },
  42. computed: {
  43. fileList: {
  44. set (val) {
  45. console.log(val);
  46. this.$emit(
  47. 'input',
  48. val.map((item) => ({
  49. ...item,
  50. url: getImagePath(item.url)
  51. }))
  52. );
  53. },
  54. get () {
  55. const arr = this.value.map((item) => ({
  56. ...item,
  57. url: getImageUrl(item.url)
  58. }));
  59. return arr;
  60. }
  61. }
  62. },
  63. methods: {
  64. beforeRemove (file) {
  65. if (file.id) {
  66. return removeFile({
  67. fileId: file.id
  68. }).then(() => {
  69. return true;
  70. });
  71. } else {
  72. return true;
  73. }
  74. },
  75. handleRemove (file, fileList) {
  76. this.fileList = fileList;
  77. },
  78. beforeUpload (file) {
  79. if (file.size / 1024 / 1024 > this.size) {
  80. this.$message.error(`大小不能超过 ${this.size}MB`);
  81. return false;
  82. }
  83. if (this.limit > 0 && this.fileList.length === this.limit) {
  84. this.$message.error(`最多上传 ${this.limit}个文件`);
  85. return false;
  86. }
  87. return uploadFile({
  88. module: this.module,
  89. multiPartFile: file
  90. }).then((res) => {
  91. if (res.data) {
  92. this.$emit('input', [
  93. ...this.value,
  94. { ...file, url: res.data.storePath, ...res.data }
  95. ]);
  96. }
  97. return res.data;
  98. });
  99. },
  100. handlRequest () {
  101. return Promise.resolve();
  102. }
  103. }
  104. };
  105. </script>