要在JavaScript中下载PDF文件流,可以使用以下方法:\n\n1. 使用Fetch API:使用Fetch API可以从服务器获取PDF文件流,并将其保存到本地。以下是一个示例代码:\n\njavascript\nfetch('http://example.com/path/to/file.pdf')\n .then(response => response.blob())\n .then(blob => {\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = 'file.pdf';\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n });\n\n\n2. 使用XMLHttpRequest:使用XMLHttpRequest对象可以发送HTTP请求并获取PDF文件流。以下是一个示例代码:\n\njavascript\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'http://example.com/path/to/file.pdf', true);\nxhr.responseType = 'blob';\n\nxhr.onload = function() {\n if (xhr.status === 200) {\n const blob = xhr.response;\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = 'file.pdf';\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n }\n};\n\nxhr.send();\n\n\n以上方法都是通过创建一个<a>元素,将文件流的URL赋值给href属性,并设置download属性来指定文件名。然后将<a>元素添加到文档中,模拟点击<a>元素以触发下载,最后从文档中删除<a>元素并释放URL。\n\n请确保将URL替换为实际的PDF文件的URL。

JavaScript下载PDF文件流 - 两种方法详解

原文地址: https://www.cveoy.top/t/topic/p6K7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录