簡體   English   中英

XMLHttpRequest 是否阻止了 Content-Disposition 附件?

[英]Is Content-Disposition attachment blocked from XMLHttpRequest?

我想從我編寫的 C# 網絡服務器對 png 文件執行 javascript xhr 請求。 這是我使用的代碼

    var imgUrl = "http://localhost:8085/AnImage.png?" + now;
    var request = new XMLHttpRequest();
    request.open('GET', imgUrl, false);
    request.send(); // this is in a try/catch

在服務器端,我發回文件並添加一個 Content-Disposition 標頭。 我得到以下回復

在響應中獲得的標頭,使用 Firebug

我確保在 Content-Type 之后的標題中附加了 Content-Disposition(截圖來自 Firebug,按字母順序附加)。

結果是沒有觸發對話框,我是不是在響應中遺漏了什么?

編輯:出於多種原因,我想在 javascript 中執行所有操作。 第一:我不想展示圖像,我想把一切都隱藏在幕后。 第二:在請求圖像時,我希望僅在特定請求時添加 Content-Disposition。 此類請求標有“警告”標頭,其值為“AttachmentRequest”

request.setRequestHeader("Warning","AttachmentRequest");

當請求是通過 XHR 時,我認為Content-Disposition不會觸發任何文件保存對話框。 XHR 的使用表明您將在代碼中處理結果。

如果您希望提示用戶將圖像保存到文件中,我已經成功地使用了此技術:

window.open("http://localhost:8085/AnImage.png?" + now);

它的缺點是它會短暫地閃爍一個空白的打開窗口,直到標題到達,然后新窗口關閉並出現“保存文件”對話框。

使用iframe可能會阻止窗口閃爍:

var f = document.createElement('iframe');
f.style.position = "absolute";
f.style.left = "-10000px";
f.src = "http://localhost:8085/AnImage.png?" + now;
document.body.appendChild(f);

另外,我想知道Content-Dispositionimg元素的處理有什么影響(如果有的話):

var img = document.createElement('img');
img.style.position = "absolute";
img.style.left = "-10000px";
img.src = "http://localhost:8085/AnImage.png?" + now;
document.body.appendChild(img);

我還沒有嘗試過,但瀏覽器可能會尊重標題。 您需要確保在您想要支持的所有瀏覽器上進行測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM