P粉0717437322023-08-17 12:50:47
The file extension actually doesn't have much to do with this... Content-Type
The header does.
Based on your description, I'm guessing that when getting PDF files, the server is not using the correct type in the response, but instead sending them as application/octet-stream
or other types. (This is a common type and browsers download them by default.)
There are several ways to solve this problem. One way is to use ServiceWorker to override the Content-Type
header as needed. However, this doesn't always work. Browsers often disable service workers when a page is forced to reload or when privacy mode is enabled.
Another approach closer to what you propose is to get the PDF in memory in JavaScript. You can do this using the Fetch API, then create a Blob URL and let the browser download it. Not tested yet, but roughly this:
const res = await fetch('https://example.com/doc.pdf.fake-ext'); if (!res.ok) { throw new Error(`${res.status} ${res.statusText}`); } const blob = await res.blob(); const blobUrl = URL.createObjectURL(blob); // 现在,您可以直接链接或重定向到`blobUrl`。 // 完成后一定要释放它,使用URL.revokeObjectURL()。
Please note that this may not work for particularly large documents. Small documents are no problem.
Also note that not all browsers can display PDF, and not all systems are configured to allow the browser to display PDF on its own.