代码之家  ›  专栏  ›  技术社区  ›  Bob

下载文件时iframe onload

  •  4
  • Bob  · 技术社区  · 15 年前

    我已经把头发拔出来好几个小时了。 我有一个iframe,我想用它下载一个文件。一切正常,但如果我的 Response.ContentType = "APPLICATION/OCTET-STREAM";

    我的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。

    感谢您的帮助。

    当做, Byron Cobb。

    1 回复  |  直到 15 年前
        1
  •  4
  •   bobince    15 年前

    嗯,是的。 onload 仅当文档加载到iframe时调用。保存操作不会将文档加载到框架中;保留旧文档并弹出“另存为”对话框。

    您无法检测到文件下载已被接受或仅从javascript完成。如果您真的需要检测到这一点,那么最接近的方法就是让服务器端以一个唯一的ID存储下载的进度,并为客户端脚本提供一个Ajax接口来查询服务器是否已经完成了文件的发送。

    顺便说一句:

    onload:'javascript:alertReady();'
    

    值得怀疑。你不需要也不应该使用 javascript: 事件处理程序属性(仅用于 href="javascript:..." URL,也不应该使用!).js中的字符串设置事件处理程序属性是非常危险的。经过 onload: alertReady 直接使用会更好,或者因为使用jquery,所以使用标准绑定方法,如 iframe.load(function() { ... }); .