index.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <template>
  2. <div class="excel-import">
  3. <el-upload
  4. class="excel-uploader"
  5. :action="uploadUrl"
  6. :headers="headers"
  7. :data="uploadData"
  8. :on-progress="handleUploadProgress"
  9. :on-success="handleUploadSuccess"
  10. :on-error="handleUploadError"
  11. :before-upload="beforeUpload"
  12. :show-file-list="false"
  13. accept=".xlsx,.xls"
  14. >
  15. <el-button type="primary" :loading="loading">
  16. <i class="el-icon-upload2" /><slot name="upload-text">上传Excel文件</slot>
  17. </el-button>
  18. <div class="el-upload__tip" slot="tip">只能上传 xlsx/xls 文件,且不超过10MB</div>
  19. </el-upload>
  20. <el-progress
  21. v-if="uploadProgress > 0 && uploadProgress < 100"
  22. :percentage="uploadProgress"
  23. :status="uploadStatus"
  24. style="margin-top: 20px"
  25. />
  26. </div>
  27. </template>
  28. <script>
  29. export default {
  30. name: 'ExcelImport',
  31. props: {
  32. uploadUrl: {
  33. type: String,
  34. required: true
  35. },
  36. uploadData: {
  37. type: Object,
  38. default: () => ({})
  39. },
  40. headers: {
  41. type: Object,
  42. default: () => ({})
  43. },
  44. maxSize: {
  45. type: Number,
  46. default: 10
  47. }
  48. },
  49. data() {
  50. return {
  51. loading: false,
  52. uploadProgress: 0,
  53. uploadStatus: null
  54. }
  55. },
  56. methods: {
  57. beforeUpload(file) {
  58. const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  59. const isLt10M = file.size / 1024 / 1024 < this.maxSize
  60. if (!isExcel) {
  61. this.$message.error('只能上传 Excel 文件!')
  62. return false
  63. }
  64. if (!isLt10M) {
  65. this.$message.error(`文件大小不能超过 ${this.maxSize}MB!`)
  66. return false
  67. }
  68. this.uploadProgress = 0
  69. this.uploadStatus = null
  70. this.loading = true;
  71. return true
  72. },
  73. handleUploadProgress(event) {
  74. this.uploadProgress = Math.floor((event.loaded / event.total) * 100)
  75. },
  76. handleUploadSuccess(response) {
  77. this.uploadStatus = 'success';
  78. this.loading = false;
  79. this.$emit('on-success', response);
  80. setTimeout(() => {
  81. this.uploadProgress = 0
  82. }, 2000)
  83. },
  84. handleUploadError() {
  85. this.loading = false;
  86. this.uploadStatus = 'exception'
  87. this.$message.error('文件上传失败')
  88. }
  89. }
  90. }
  91. </script>
  92. <style scoped>
  93. .excel-uploader {
  94. display: flex;
  95. align-items: center;
  96. gap: 10px;
  97. }
  98. .el-upload__tip {
  99. color: #909399;
  100. font-size: 12px;
  101. margin: 0;
  102. }
  103. </style>