Iframe加载文件时的onload事件

4

我已经为了解决这个问题而苦思冥想了几个小时。
我有一个包含下载文件的iframe。一切都很好,但是如果我的Response.ContentType = "APPLICATION/OCTET-STREAM";,则不会调用iframe onload事件。

我的javascript函数如下:

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");
}

我的服务器端代码如下:

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);

如果我删除ContentType和Header,那么onload会被调用,但是文件将不会通过保存文件对话框下载,而是写入iframe中。
非常感谢您的帮助。
祝好, 拜伦·科布。
1个回答

4

是的。只有当文档加载到iframe中时,才会调用onload。保存操作不会将文档加载到框架中;旧文档仍然保留在原地,并弹出另存为对话框。

你无法仅通过JavaScript检测文件下载是否已被接受或完成。如果你真的需要检测这个,最接近的方法是让服务器端使用唯一ID存储下载进度,并提供一个AJAX接口,以便客户端脚本查询服务器是否已经完成文件发送。

顺便说一下:

onload:'javascript:alertReady();'

存在一些问题。在事件处理程序属性中,您不需要也不应该使用javascript:(这仅适用于href="javascript:..." URL,这也永远不应该使用!)。从JS设置事件处理程序属性为字符串是非常危险的。直接传递onload: alertReady会更好,或者由于您正在使用jQuery,请使用标准绑定方法,如 iframe.load(function() { ... });


谢谢。我这样设置我的onload是因为在意识到是contenttype的问题之前,我尝试了所有可能的onload解决方案。 - Bob
我问了类似的问题 http://stackoverflow.com/questions/17184970/iframe-onload-wont-fire-when-dumping-a-file - Royi Namir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接