| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <template>
- <div class="excel-import">
- <el-upload
- class="excel-uploader"
- :action="uploadUrl"
- :headers="headers"
- :data="uploadData"
- :on-progress="handleUploadProgress"
- :on-success="handleUploadSuccess"
- :on-error="handleUploadError"
- :before-upload="beforeUpload"
- :show-file-list="false"
- accept=".xlsx,.xls"
- >
- <el-button type="primary" :loading="loading">
- <i class="el-icon-upload2" /><slot name="upload-text">上传Excel文件</slot>
- </el-button>
- <div class="el-upload__tip" slot="tip">只能上传 xlsx/xls 文件,且不超过10MB</div>
- </el-upload>
-
- <el-progress
- v-if="uploadProgress > 0 && uploadProgress < 100"
- :percentage="uploadProgress"
- :status="uploadStatus"
- style="margin-top: 20px"
- />
- </div>
- </template>
- <script>
- export default {
- name: 'ExcelImport',
- props: {
- uploadUrl: {
- type: String,
- required: true
- },
- uploadData: {
- type: Object,
- default: () => ({})
- },
- headers: {
- type: Object,
- default: () => ({})
- },
- maxSize: {
- type: Number,
- default: 10
- }
- },
- data() {
- return {
- loading: false,
- uploadProgress: 0,
- uploadStatus: null
- }
- },
- methods: {
- beforeUpload(file) {
- const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
- const isLt10M = file.size / 1024 / 1024 < this.maxSize
- if (!isExcel) {
- this.$message.error('只能上传 Excel 文件!')
- return false
- }
- if (!isLt10M) {
- this.$message.error(`文件大小不能超过 ${this.maxSize}MB!`)
- return false
- }
-
- this.uploadProgress = 0
- this.uploadStatus = null
- this.loading = true;
- return true
- },
-
- handleUploadProgress(event) {
- this.uploadProgress = Math.floor((event.loaded / event.total) * 100)
- },
-
- handleUploadSuccess(response) {
- this.uploadStatus = 'success';
- this.loading = false;
- this.$emit('on-success', response);
- setTimeout(() => {
- this.uploadProgress = 0
- }, 2000)
- },
-
- handleUploadError() {
- this.loading = false;
- this.uploadStatus = 'exception'
- this.$message.error('文件上传失败')
- }
- }
- }
- </script>
- <style scoped>
- .excel-uploader {
- display: flex;
- align-items: center;
- gap: 10px;
- }
- .el-upload__tip {
- color: #909399;
- font-size: 12px;
- margin: 0;
- }
- </style>
|