附件下载 el-upload ------ 导入功能实现

143 阅读1分钟

附件下载 el-upload ------ 导入功能实现

image.png

image.png 实现代码

<el-upload
                                    ref="upload"
                                    class="upload-demo"
                                    :data="drData"
                                    :show-file-list="false"
                                    :action="actionUrl"
                                    :headers="headers"
                                    :auto-upload="false" 
                                    :before-upload="beforeAvatarUpload"
                                    :http-request="uploadSectionFile"
                                    :on-change="filesChange"
                                    :on-success="handleSuccess"
                                    :on-error="handleError"
                                    accept=".xls,.xlsx"
                                >
                                    <el-button size="small" type="primary"
                                        >选择文件</el-button
                                    >
                                    <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
                                </el-upload>

使用 自定义上传为 http-request

data 中 定义 需要上传的 参数 
  drData: {
                fileName:'',
                bz:'',
            },
  actionUrl: `后端提供的上传接口/importFile`,
   headers: {
                backdoor: 1,
                'access-token': getToken()
            }, //  上传的请求头部

一些上传时候的钩子函数

 beforeAvatarUpload(file) {
            // 上传文件之前的钩子,只能上传 excel
            if (
                file.type !==
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' &&
                file.type !== 'application/vnd.ms-excel'
            ) {
                this.$message({
                    showClose: true,
                    message: '请上传Excel文件',
                    type: 'warning'
                });
                return false;
            }
            // this.drData.file = file.name;
            // console.log(' this.drData.file ', this.drData.file);

        },
        handleSuccess(response, file, fileList) {
            console.log(response, file, fileList);
            // 文件上传成功时的钩子
            this.msg = response.msg;
            // '本次导入数据' +
            // response.drsl +
            // '条,入库' +
            // response.rksl +
            // '条,错误' +
            // response.cwsl +
            // '条,请查看数据';
            this.$message({
                showClose: true,
                message: '上传成功',
                type: 'success'
            });
            this.assignDialogBool = false;
            this.drData = {};
            this.getlist();
            this.$refs['dataForm'].clearValidate(['file']);
        },
        handleError(err, file, fileList) {
            console.log('22222');
            // 上传失败时
            this.$message({
                showClose: true,
                message: '导入失败',
                type: 'warning'
            });
        },

然后使用 自定义 上传 需要使用formData 方法 上传成功提示 上传成功 上传失败 根据后端返回的数据流下载出来

uploadSectionFile(params){
            const _file = params.file;
            // 通过 FormData 对象上传文件
            // console.log('this.drData.bz',this.drData.bz);
            var formData = new FormData();
            formData.append('file', _file);
            formData.append('drrq', this.drData.drrq);
            formData.append('fileType', this.drData.fileType);
            formData.append('fileName', this.drData.fileName);
            formData.append('bz', this.drData.bz);
            // formData.append('responseType', 'blob');
            console.log(formData.get('bz'),'bz');
            // 请求路径
            let url = `${this.actionUrl}`;
            this.uploadExcel(url, formData).then(async (res) => {
                console.log(res,'res');
                // 成功res是'true'  失败是blob类型
                if (res[0] == 'true') {
                    this.$message({
                        message:'文件导入成功',
                        type:'success',
                        duration:3000
                    });
                    this.assignDialogBool = false;
                    // this.drData = {};
                    this.getlist();
                    // this.tableData.result =  [...this.tableData.result,...res[1]];
                    console.log(res[1]);
                    // this.tableData.result =  res[1];
                    
                    // console.log(res);
                } else {
                    try {
                        await this.$confirm('导入文件内容错误,是否下载错误文件!', '提示', {
                            confirmButtonText: '出错附件下载',
                            cancelButtonText: '关闭',
                            type: 'warning',
                        });
                        // 下载出错附件
                        const fileName = '导入错误文件.xls';
                        const blob = new Blob([res], {
                            type: 'application/vnd.ms-excel',
                        });
                        if (window.navigator.msSaveOrOpenBlob) {
                            navigator.msSaveBlob(blob, fileName);
                        } else {
                            console.log('blob==',blob);    
                            var link = document.createElement('a');
                           
                            link.href = window.URL.createObjectURL(blob);
                            console.log('window.URL.createObjectURL(blob)1111==',window.URL.createObjectURL(blob));    
                            link.download = fileName;
                            link.click();
                            // 释放内存
                            window.URL.revokeObjectURL(link.href);
                        }
                        this.assignDialogBool = false;

                    } catch (e) {
                        this.$message.info('操作取消');
                    }
                }
            }).catch(err=>{
                // console.log(err,'err');
                this.errsize = true;
                // this.$message.warning('模板出错,请重新选择模板文件');
            }
            ); 

        },
uploadExcel(url, formData) {
            return new Promise((resolve, reject) => {
                post(url, {
                    data:formData,
                    responseType: 'blob',
                    headers: {
                        backdoor: 1,
                    },
                }).then(
                    async res => {
                        // eslint-disable-next-line require-jsdoc
                        function blobToBase64 (res) {
                            var blob = new Blob([res], { type: 'application/json' });
                            return new Promise((resolve, reject) => {
                                const fileReader = new FileReader();
                                fileReader.onload = (e) => {
                                // console.log(e.target.result, '88///');
                                    resolve(e.target.result);
                                };
                                fileReader.readAsText(blob);
                                fileReader.onerror = () => {
                                    reject(new Error('blobToBase64 error'));
                                };
                            });
                        };
                
                        let isSuccess = await blobToBase64(res);
                        try{
                            const resData = JSON.parse(isSuccess);
                            // console.log(resData);
                            resolve(['true',resData]);
                        }catch(e){
                            // 导入失败返回流
                            // resolve(['false',res]);
                            resolve(res);
                        }
                        
                        // if(isSuccess === 'true'){
                        //     // 导入成功
                        //     resolve('true');
                        // } else {
                        //     // 导入失败返回流
                        //     resolve(res);
                        // }
                    },
                    (err) => {
                        reject(err);
                        // console.log(err,'wwww');
                    });
            });
        }