js直接下载PDF(不打开浏览器预览)

1,141 阅读1分钟

js直接下载PDF(不打开浏览器预览)

//直接下载PDF,不预览
     downPdf() {
        let data = {
            url:'http://'+this.auctionInfo.registration,
            type:'pdf',
            name:'pdf文件名称'
        }
        fetch(data.url, {
            method: "get",
            mode: "cors",
        })
            .then((response) => response.blob())
            .then((res) => {
                const downloadUrl = window.URL.createObjectURL(
                    new Blob([res], {
                        type: data.type == "pdf" ? "application/pdf" : ""
                    })
                );
                const link = document.createElement("a");
                link.href = downloadUrl;
                link.setAttribute("download", data.name);
                document.body.appendChild(link);
                link.click();
                link.remove();
            }).catch((error) => {
                window.open(url);
            });

     },