Ajax 如何处理来自XMLHttpRequest的八位字节流

Ajax 如何处理来自XMLHttpRequest的八位字节流,ajax,iframe,xmlhttprequest,download,Ajax,Iframe,Xmlhttprequest,Download,我想通过AJAX调用从服务器下载文件。 使用iframe可轻松完成,如下所示: var ifrm = document.getElementById("fileframe"); ifrm.src = "DownloadFile?fileid="+fileid; 但我有更复杂的问题。 在某些情况下,后端将返回内容类型为“text/html”的响应,而不是应用程序/octet流 我计划使用XMLHttpRequest调用backed来下载文件。 通过使用XMLHttpRequest如何使浏览器弹

我想通过AJAX调用从服务器下载文件。 使用
iframe
可轻松完成,如下所示:

var ifrm = document.getElementById("fileframe"); 
ifrm.src = "DownloadFile?fileid="+fileid;
但我有更复杂的问题。 在某些情况下,后端将返回内容类型为“text/html”的响应,而不是应用程序/octet流

我计划使用
XMLHttpRequest
调用backed来下载文件。 通过使用
XMLHttpRequest
如何使浏览器弹出保存文件对话框来处理应用程序/八位字节流

// connect function handles the XMLHttpRequest communication with the backend
var connection = connect('DownloadFile','fileid='+fileid); 
connection.onreadystatechange = function(){
    if(connection.readyState == 4) { 
        var contentType = connection.getResponseHeader('Content-Type');
        if(contentType == 'application/octet-stream'){
           // here I want to make the browser popup a save file dialog
           // for the incoming octet stream
           // maybe I can direct stream to an iframe, but how??

        }else{
           alert(connection.responseText);
        }
    }
    if((connection.readyState == 2)||(connection.readyState == 3)){
    }
}

我可以想出两个选择

  • 首先发送HEAD请求,并根据内容决定操作 类型。
    发出一个GET请求,知道会发生什么
  • 创建一个数据源 URI(RFC 2387)和数据,并使用window.open打开它。
    浏览器将为无法呈现的内容打开一个对话框

  • 我可以想出两个选择

  • 首先发送HEAD请求,并根据内容决定操作 类型。
    发出一个GET请求,知道会发生什么
  • 创建一个数据源 URI(RFC 2387)和数据,并使用window.open打开它。
    浏览器将为无法呈现的内容打开一个对话框