[英]XMLHttpRequest to open PDF in browser
我想做 XMLHttpRequest,然后通過 POST 方法發送文件名在瀏覽器中打開 PDF。
xmlhttp.open("POST","pdf.php",true); //CHANGE
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("file="+input);
這是可能的還是 XMLHttpRequest 僅適用於 HTML?
如果您查詢的 URL 實際返回 PDF 數據,則無法通過 XMLHttpRequest 執行此操作。
為什么? 因為響應是包含原始 PDF 數據的 HTTP 響應。 JavaScript 無法將當前文檔的 DOM 內容替換為包含在該數據中的 PDF 的呈現,即使您確實可以通過responseText ` 屬性訪問數據(另請參閱http://www.w3.org/TR /XMLHttpRequest/#the-responsetext-attribute )。
您可以做的是將 PDF 文件生成為可通過 Web 服務器的 URL 訪問的臨時文件,然后讓腳本發回用於訪問該文件的 URL。
當您的響應處理程序處理 URL 時,它可以:
通過更改window.location.href = new_pdf_url
重新加載當前頁面
通過更改 iframe 的src
屬性將其加載到當前文檔內的<iframe>
通過window.open(new_pdf_url, XXX)
在單獨的窗口中打開它
請注意,您仍然需要一個指向臨時文件位置的 URL 才能打開新窗口
如果您在同一窗口中打開 PDF,則無需使用 XmlHttpRequest,只需設置 window.location ( window.location.assign("http://example.com/location/file.pdf")
, window.location.href="http://etc
),而不是調用 XmlHttpRequest。(如果您已從 XmlHttpRequest 收到 PDF 字節,您將如何說服瀏覽器使用 PdfPluginX 顯示它?)
如果您想在新的瀏覽器窗口中使用 PDF,只需直接從您的 javascript 使用window.open(...)
。
是的,可以這樣做,首先您需要將文件作為 arrayBuffer 獲取,然后使用新的 blob 創建一個對象 url,然后分配給 src。
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.type = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200){
var blobSrc = window.URL.createObjectURL(new Blob([this.response], { type: 'application/pdf' }));
// assign to your iframe or to window.open
yourIframe.src = blobSrc;
}
你可以試試這個:
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var file = window.URL.createObjectURL(xmlHttp.response);
var a = document.createElement("a");
a.href = file; window.open(file);
}
}
xmlHttp.open("GET", '/pdf', true); // true for asynchronous xmlHttp.responseType= "blob";
xmlHttp.send(null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.