文件流下载

        // 文件下载
        downloadExecl(res) {
            const { data, headers } = res;
            const contentDisposition = headers['content-disposition'];
            const encodeFileName = decodeURIComponent(contentDisposition);
            const fileName = encodeFileName.replace('attachment;fileName=', '');
            const link = document.createElement('a');
            const blob = new Blob([data], { type: 'application/vnd.ms-excel' });
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', `${fileName}`); // 报表名称可自定义
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
 
 
          this.batchDeviceExport(params).then(res => {
                this.exportBtn = false;
                if (res.data) {
                    let formData = new FormData();
                    formData.append('data', res.data, {
                        type: 'application/json'
                    });
                    let data = new FileReader();
                    data.readAsText(formData.get('data'), 'utf-8');
                    data.onload = () => {
                        let result = '';
                        let isExport = true; // 是否导出成功
                        try {
                            result = JSON.parse(data.result);
                            isExport = false;
                        } catch (error) {
                            result = data.result;
                            isExport = true;
                        }
                        console.log(result);
                        if (isExport) {
                            this.downloadExecl(res);
                        } else {
                            let formData = new FormData();
                            formData.append('data', res.data, {
                                type: 'application/json'
                            });
                            let data = new FileReader();
                            data.readAsText(formData.get('data'), 'utf-8');
                            data.onload = () => {
                                const { msg, success } = JSON.parse(data.result);
                                if (!success) {
                                    this.$message.error(msg || '服务器异常');
                                }

                            };
                        }
                    };
                }
            }).catch(e => {
                this.exportBtn = false;
                this.$message.error('服务器异常');
            });
posted @ 2024-10-29 15:33  BGweizheng  阅读(20)  评论(0)    收藏  举报