views:

37

answers:

1

Hi there!

I've been pulling my hair out for hours trying to figure this out. I have an iframe with which I want to download a file. It all works fine, but the iframe onload is not called if my Response.ContentType = "APPLICATION/OCTET-STREAM";

My javascript function is as follows:

function DownloadStuff(){
var DownloadSource = "http://Apage.aspx"
        var iframe = $("#hiddenDownloader");
        if (iframe.attr("id") === undefined) {
            $('<iframe />', { id: 'hiddenDownloader',  onload:'javascript:alertReady();' }).appendTo('body');
            iframe = $("#hiddenDownloader");
        }
iframe.attr('src', DownloadSource);
}

function alertReady() {
    alert("Ready");
}

My server side code is as follows:

Response.Clear();
Response.CacheControl = "no-cache";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetValidUntilExpires(false);
Response.ExpiresAbsolute = DateTime.Parse("1/1/2000");
Response.Expires = 0;
Response.ContentType = "APPLICATION/OCTET-STREAM";
Response.AddHeader("Content-Disposition", "attachment;filename=\"ReportDeck.pptx\"");
byte[] bytes = (byte[])PowerPointFile.Tables[0].Rows[0]["PPTBlob"];
bytes = Compression.DeCompressByteArray(bytes);
Response.OutputStream.Write(bytes, 0, bytes.Length);

If I remove the ContentType and Header the onload is called, but then the file is not downloaded through the save file dialog, but is instead written into the iframe.

Any help is appreciated.

Regards, Byron Cobb.

+2  A: 

Well yeah. onload is only called when a document is loaded into an iframe. A Save operation does not load a document into the frame; the old document is left in place and the save-as dialogue is popped-up.

You cannot detect that a file download has been accepted or completed from JavaScript alone. If you really need to detect that, the closest you would be able to get would be to have to have the server-side store the progress of the download by a unique ID, and provide an AJAX interface for the client-side script to query whether the server had finished sending the file yet.

Incidentally:

onload:'javascript:alertReady();'

is doubtful. You don't need and shouldn't use javascript: in event handler attributes (that's only for href="javascript:..." URLs, which should also never be used!). And setting an event handler attribute to a string from JS is highly dodgy. Passing onload: alertReady directly would be better, or since you're using jQuery use the standard binding methods like iframe.load(function() { ... });.

bobince
Thanks. I have my onload that way because I was trying all possible solutions for onload before I realized it was because of the contenttype.
Byron Cobb