【发布时间】:2012-04-04 21:41:46
【问题描述】:
我想通过 AJAX 调用从服务器下载文件。
使用iframe 可以轻松完成,如下所示:
var ifrm = document.getElementById("fileframe");
ifrm.src = "DownloadFile?fileid="+fileid;
但我有更复杂的问题。 在某些情况下,后端会返回内容类型为“text/html”的响应,而不是 application/octet-stream。
我计划使用XMLHttpRequest 调用支持下载文件。
通过使用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)){
}
}
【问题讨论】:
标签: ajax iframe xmlhttprequest download