首页 文章

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

提问于
浏览
2

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

var ifrm = document.getElementById("fileframe"); 
ifrm.src = "DownloadFile?fileid="+fileid;

但我有更复杂的问题 . 在某些情况下,后端会返回内容类型为'text/html'的响应,而不是 application/octet-stream .

我计划使用 XMLHttpRequest 调用支持下载文件 . 通过使用 XMLHttpRequest 如何让浏览器弹出一个保存文件对话框来处理application / octet-stream?

// 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)){
    }
}

1 回答

  • 0

    我可以想到两个选择 .

    • 首先发送HEAD请求,然后根据内容类型决定操作 .
      发出GET请求,知道会发生什么 .

    • 使用数据创建数据URI(RFC 2387)并使用window.open打开它 .
      浏览器将打开一个无法呈现内容的对话框 .

相关问题