我有一個輸入 URL,我想用它直接下載 pdf 檔案,而無需在新選項卡或同一選項卡中查看它,到目前為止我一直在嘗試以下操作,但沒有任何幫助。首先嘗試過這個
http.success(function (data) {
var link = document.createElement('a');
link.href = data.results[0].value.url;
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
此腳本未下載檔案。它在同一選項卡中打開檔案。已經嘗試了這些先前回答的問題中的所有答案。但沒有什么對我有用。 如何使用javascript從url下載pdf? 如何使用js自動下載PDF? 無需在瀏覽器中打開即可下載pdf
然后我嘗試了這個Blob。將 blob 添加到我的腳本中,然后再試一次。
http.success(function (data) {
var blob=new Blob([data.results[0].value.url],{ type: "application/pdf" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') 1);
link.click();
document.body.appendChild(link);
setTimeout(function () {
document.body.removeChild(link);
}, 100);
}.bind(this));
但這次它下載了檔案。但是打不開。下載的檔案已損壞。已經嘗試了這些問題中的答案。但沒有什么對我有用。 使用 URL.createObjectURL 重建 PDF 后,PDF 已損壞 問題在 JavaScript Blob 中從緩沖區下載 PDF blob回傳損壞的 pdf
請讓我知道是否有任何其他方法可以直接下載 pdf 檔案。提前致謝。
uj5u.com熱心網友回復:
data.results[0].value.url 中存盤了什么?
它只是指向PDF的鏈接嗎?如果是這種情況,您需要先獲取 pdf 檔案。
嘗試這個
http.success(function (data) {
fetch(data.results[0].value.url)
.then((response) => response.arrayBuffer())
.then((pdfFile) => {
const blob = new Blob([pdfFile], { type: "application/pdf" });
const anchor = document.createElement("a");
anchor.href = window.URL.createObjectURL(blob);
anchor.download = "SOME FILENAME.PDF";
// some browser needs the anchor to be in the doc
document.body.append(anchor);
anchor.click();
anchor.remove();
// in case the Blob uses a lot of memory
window.addEventListener(
"focus",
() => {
URL.revokeObjectURL(anchor.href);
},
{
once: true,
}
)
});
})
uj5u.com熱心網友回復:
首先,我建議嘗試最簡單的例子。
const pdfLink = data.results[0].value.url
const download = (url) => {
const link = document.createElement('a');
link.setAttribute('download', 'fileName.pdf');
link.setAttribute('href', url);
link.click();
}
downloadBlob = (blob) => download(URL.createObjectURL(blob))
fetch(pdfLink)
.then(response => response.blob())
.then(downloadBlob)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323936.html
標籤:javascript pdf
