需求:點擊導出pdf按鈕,彈出系統文件夾彈框,可以選擇保存文件的位置。
經查詢window.showSaveFilePicker可實現,但這個api處于實驗階段,且用下來確實和瀏覽器類型、瀏覽器版本、以及本身api就不穩定有關系。
代碼見下:
<el-button @click="handleExportPdf">導出pdf</el-button>api.js接口文件:
// 獲取PDF流
export function getHistoryCheckPdf(params) {return request({method: "post",url: `${baseUrlReportApp}docReport/gainReportPdf`,responseType: "arraybuffer",//指定響應流的類型data: params});
}
// node上傳PDF文件流打印接口
export function nodePrintFile(data) {return request({baseURL: 'http://localhost:3080/printPdf', // 直接通過覆蓋的方式data,method: 'post'})
}<script>
import { getHistoryCheckPdf,nodePrintFile } from "@/api";
export default {methods:{handleExportPdf(){this.fetchPDF();},async fetchPDF(isCloseReport) {getHistoryCheckPdf({stReportSoid: this.initializeInfo.stReportSoid,requestSoid: createListRequestSoid(this.initializeInfo)[0],}).then((res) => {if (res.byteLength < 10) {this.$message({message: "PDF未獲取到,請稍后重試!",type: "warning",});return;}// 保存pdf到本地文件夾this.savePDF(res);// 打印pdf方法// this.handlerNodeResPrint(res, isCloseReport);});}}
},// 保存文件到指定位置async savePDF(res) {let curTime = moment().format("YYYY-MM-DD HH:mm:ss");let timeList = curTime.split(" ");let dateItem = timeList[0].split("-").join("");let timeItem = timeList[1].split(":").join("");let finaDate = dateItem + timeItem;let pdfName = finaDate + ".pdf";// ①保存文件到默認位置var blob = new Blob([res], { type: "application/octet-stream" });var url = window.URL.createObjectURL(blob);var link = document.createElement("a");link.href = url;link.download = pdfName;document.body.appendChild(link);link.click();document.body.removeChild(link);window.URL.revokeObjectURL(url);// ②保存文件到指定位置:不穩定,未使用// window.showSaveFilePicker此api尚在實驗中,只支持https,且對瀏覽器有兼容// try {// const opts = {// types: [// {// description: "文件",// accept: {// "text/plain": [".txt"],// "application/pdf": [".pdf"],// "image/jpeg": [".jpg", ".jpeg"],// "image/png": [".png"],// },// },// ],// excludeAcceptAllOption: true,// suggestedName: pdfName,// };// const handle = await window.showSaveFilePicker(opts); // 打開保存文件對話框// const writable = await handle.createWritable(); // 創建可寫入的文件對象// // 在這里寫入文件內容// await writable.write(res);// await writable.close();// console.log("文件保存成功");// this.$message.success("文件保存成功");// } catch (error) {// console.error("文件保存失敗:", error);// }},//打印方法handlerNodeResPrint(buffer, isCloseReport) {const formData = new FormData();formData.append("file", new Blob([buffer]));// formData.append("printName", "");formData.append("fileType", "pdf");formData.append("type", "server");formData.append("orientation", "landscape");formData.append("paperSize", "A5");// Node打印nodePrintFile(formData).then((res) => {if (res.code == 200) {this.$message.success("打印成功!!!");} else {this.$message.error(res.message);}});},},</script>