后端返回文件流和json格式的方式进行文件下载导出
fetch({ url: this.exportUrl, method: "post", data: obj, noFormat: true, headers: { "Content-Type": "application/json; application/octet-stream" }, responseType: "arraybuffer" }).then(result => { if (result.data.error_code) { this.$hMessage.error(result.data.error_message || "导出失败!"); return; } var b = new Blob([result.data], { type: "application/vnd.ms-excel" }); // 根据传入的参数b创建一个指向该参数对象的URL var url = URL.createObjectURL(b); var link = document.createElement("a"); // 导出的文件名 let fileName = "demo.xlsx"; link.download = fileName; link.href = url; link.click(); });
1. 接口返回的类型是文件流的格式
fetch({ url: this.exportUrl, method: "post", data: obj, noFormat: true, responseType: "json" }).then(result => { if (result.data.error_code) { this.$hMessage.error(result.data.error_message || "导出失败!"); return; } // 核心 将base64的字符串转为文件流 function dataURLtoBlob(base64Str) { var bstr = atob(base64Str), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } // 下载的是excel格式的文件 return new Blob([u8arr], { type: "application/vnd.ms-excel" }); } var blob = dataURLtoBlob(result.data.result.base64); var downloadUrl = window.URL.createObjectURL(blob); var anchor = document.createElement("a"); anchor.href = downloadUrl; anchor.download = decodeURI(result.data.result.filename); anchor.click(); // window.URL.revokeObjectURL(blob); }).catch((e) => { this.$hMessage.error(e || "导出失败!"); });
2. 接口返回的类型是json格式,里面字段对应base64格式的文件
$objPHPExcel->getActiveSheet()->setTitle('productaccess'); //设置sheet的名称 $objPHPExcel->setActiveSheetIndex(0); //设置sheet的起始位置 $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007"); ob_start(); $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件 $buf1 = ob_get_contents(); ob_end_clean(); return $this->returnData(0, '成功', ['data' => base64_encode($buf1)]);