How to handle octet-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)){
    }
}

Answers


I can think of two options.

  1. Send a HEAD request first and decide the action based on content type. Issue a GET request knowing what to expect.
  2. 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.

Need Your Help

Strange behaviour with border-collapse and colspan

html css html-table

I am trying to make an organisational chart in HTML. The code is fairly simple, but I have some problems with the rendering in Chrome/Safari and Opera.

hive hadoop permissions not correct

hadoop hive ubuntu-14.04 kylin

I installed apache kylin which requires Hadoop, hove, hbase and java to work. All things are installed correctly. Now when I try to run this example. I get error after the first command ie ${KYLIN_...