stream coming from XMLHttpRequest

I want to download files from server with AJAX calls. It can be done easily by using iframe as follow:

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

But I have more complicated issue. In some cases, instead of application/octet-stream , response with content type of 'text/html' is given back by the back end.

I plan to use XMLHttpRequest calls to the backed for downloading files. By using XMLHttpRequest how can I make a browser to popup a save file dialog to handle 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)){
    }
}

I can think of two options.

  • Send a HEAD request first and decide the action based on content type.
    Issue a GET request knowing what to expect.
  • Create a Data URI (RFC 2387) with the data and open it using window.open.
    Browser will open a dialog box for content it cannot render.
  • 链接地址: http://www.djcxy.com/p/46264.html

    上一篇: AWS S3:使用'响应强制文件下载

    下一篇: 来自XMLHttpRequest的流