el-upload文件导入前弹窗确认;导入文件过程中全局进行加载;向后端导入excel;

本文介绍了如何在前端使用Element UI实现文件上传功能,包括导入前的确认弹窗,上传过程中的全局加载,以及成功或失败后的响应。重点讲解了如何通过axios发送POST请求将Excel文件上传到后端并处理返回结果。

关键代码

相关页面代码
<el-upload action="string" :http-request="uploadFile" ref="fileRefs" :on-change="uploadFileCha"
          :limit="1" :show-file-list="false" accept=".xls, .xlsx">
    <el-button type="success" size="mini" @click.stop="beforeUploadFile" v-loading.fullscreen.lock="Fullloading"
               element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">导入</el-button>
</el-upload>
文件导入前进行弹窗确认
// 导入文件前所执行的操作
beforeUploadFile() {
    this.$confirm("确认继续进行导入文件?", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        this.$refs['fileRefs'].$refs['upload-inner'].handleClick()
    }).catch(() => {
        this.$message({
            type: 'info',
            message: '已取消导入'
        })
    })
},

当进行上传文件操作后进行全局加载操作

uploadFileCha() {
    this.Fullloading = true
}

向后端导入excel

// 后端导入excel
uploadFile(param) {
   // 清楚所上传的文件列表,防止不能进行二次上传
   this.$refs.fileRefs.clearFiles();
   let _this = this
   const File = param.file
   let formData = new FormData()
   formData.append('file', File)
   $.ajax({
       url: '后端给前端的相关接口信息',
       type: 'POST',
       data: formData,
       dataType: 'JSON',
       // 必须为false,这样才会自动加上正确的ContentType,否则服务器无法识别
       contentType: false,
       // processData必须为false,这样才能避开jQuery对formdata的默认处理,
       // XMLHttpRequest会对formdata进行正确处理
       processData: false,
       async: true,
       success: function(res) {
       		//将全局加载图表消失
       		_this.Fullloading = false
           if(res.result === 'success') {
               _this.$message({
                   type: 'success',
                   message: '数据导入成功!'
               })
           } else {
               _this.$message({
                   type: 'error',
                   message: '数据导入失败!'
               })
           }
       }
   })
},
### 端配置 el-upload 组件 在 Vue 中使用 `el-upload` 组件实现文件上传时,需要正确配置相关属性以确保文件能够顺利发送到后端。通过设置 `action` 指定上传接口地址,并限制文件类型为 `.xlsx` 或 `.xls`。 ```html <el-upload ref="upload" action="/api/upload-excel" <!-- 替换为实际接口地址 --> accept=".xlsx, .xls" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" :auto-upload="true" > <el-button type="primary">点击上传</el-button> </el-upload> ``` 其中,`accept` 属性用于限制上传文件格式;`beforeUpload` 可以进行文件校验或预处理操作;`on-success` 和 `on-error` 分别处理成功与失败的响应[^2]。 --- ### 文件上传处理逻辑 在 `beforeUpload` 钩子中可以对上传文件进行类型和大小检查,防止不符合要求的文件上传。如果需要端解析 Excel 文件内容,则可以借助 `XLSX`(即 `sheetjs`)库实现。 ```javascript import XLSX from 'xlsx'; function beforeUpload(file) { const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'].includes(file.type); const isValidSize = file.size / 1024 / 1024 < 10; // 限制为10MB以内 if (!isValidType) { this.$message.error('只能上传Excel文件'); return false; } if (!isValidSize) { this.$message.error('文件大小不能超过10MB'); return false; } // 解析Excel文件为JSON const reader = new FileReader(); reader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array' }); const sheetName = workbook.SheetNames[0]; const json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]); console.log(json); // 打印解析后的数据 }; reader.readAsArrayBuffer(file); return true; } ``` 该方法可以在上传读取并解析 Excel 数据,便于进行初步验证或展示预览效果[^2]。 --- ### 后端接收与响应处理 后端接收到上传的 `.xlsx` 文件后,可对其进行业务逻辑处理(如数据导入数据库),并在完成后返回新的 Excel 文件流供用户下载。此时需正确设置响应头以支持浏览器识别文件名及下载行为。 ```java static void setExcelDownLoadResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx"); } ``` 此方法确保浏览器能够正确识别文件名(包括中文字符),并触发下载动作[^4]。 --- ### 端接收文件流并触发下载 当后端返回的是文件流时,端应将其转换为 Blob 对象,并通过创建 `<a>` 标签的方式触发下载。 ```javascript function handleSuccess(response, file) { const blob = new Blob([response]); const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.setAttribute('download', 'result.xlsx'); // 设置默认文件名 document.body.appendChild(link); link.click(); window.URL.revokeObjectURL(link.href); document.body.removeChild(link); } ``` 这种方式适用于后端返回二进制文件流的场景,能有效避免乱码问题并提升用户体验[^4]。 --- ### 自定义上传方式 如果希望将上传逻辑与表单提交绑定在一起,而不是立即上传文件,则可以通过自定义上传函数来控制整个流程。例如: ```html <el-upload ref="upload" action="#" :http-request="customUpload" :auto-upload="false" > <el-button slot="trigger" type="primary">选取文件</el-button> <el-button @click="submitForm">提交</el-button> </el-upload> ``` ```javascript function customUpload(options) { const formData = new FormData(); formData.append('file', options.file); axios.post('/api/upload-excel', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(res => { this.$message.success('上传成功'); }).catch(err => { this.$message.error('上传失败'); }); } function submitForm() { this.$refs.upload.submit(); // 触发上传 } ``` 这种做法允许更灵活地控制上传时机,比如等待用户填写完其他表单项后再执行上传操作[^3]。 --- ### 相关问题 1. 如何在 Vue 中使用 `el-upload` 组件实现多文件上传并批量处理? 2. 使用 `XLSX` 解析 Excel 文件时如何处理日期格式不一致的问题? 3. 端如何通过 `Blob` 对象实现从后端下载 PDF 文件? 4. 在 Vue 项目中如何处理大体积 Excel 文件上传导致页面卡顿的问题?
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值