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

从aspx页面下载PDF

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

    我有一个页面,当用户点击一个按钮时,会动态生成一个PDF供他们下载。

    这是允许用户下载pdf的代码:

    // Omitted code that generates the pdf bytes
    
    response.ContentType = "application/octetstream";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
    response.BinaryWrite(pdfBytes);
    response.End();
    

    在我的机器和其他许多使用Chrome、IE 7/8/9b和Firefox的混合软件的机器上,这一切都如期进行;用户点击按钮,PDF文件就会被下载。

    在IE7的某些实例中,我们的用户报告他们收到了一条错误消息:

    “Internet Explorer无法从site.com下载Publish.aspx

    Internet Explorer无法打开此Internet站点。请求的站点不可用或找不到。请稍后再试”。

    Publish.aspx是按钮所在的页面,因此该页面 可用。IE应该下载pdf。

    上面的代码有什么问题可能导致某些机器上出现这种情况吗?还是取决于特定的安全/操作系统/浏览器设置?

    编辑:

    以下是fiddler的响应头:

    HTTP/1.1 200 OK
    Cache-Control: no-cache, no-store, must-revalidate
    Pragma: no-cache
    Content-Type: application/octetstream
    Expires: -1
    Server: Microsoft-IIS/7.5
    Content-Disposition: attachment; filename=myPdf.pdf
    X-AspNet-Version: 2.0.50727
    X-Powered-By: ASP.NET
    Date: Fri, 12 Nov 2010 09:48:06 GMT
    Content-Length: 45772
    
    7 回复  |  直到 15 年前
        1
  •  2
  •   Joop    15 年前

    最近我碰到了同样的错误。在我的例子中,我使用的是https,没有缓存。不下载文件似乎是IE的一个安全特性。从埃里克洛的内部:

    如果用户试图通过HTTPS连接下载*文件,任何阻止缓存的响应头都将导致文件下载过程失败。

    http://blogs.msdn.com/b/ieinternals/archive/2009/10/02/internet-explorer-cannot-download-over-https-when-no-cache.aspx

        2
  •  3
  •   Nicolas Repiquet    15 年前

    可能是因为正确的mime类型是 application/octet-stream ,不是 application/octetstream .

        3
  •  2
  •   Aneef    15 年前

    尝试使用Response.OutputStream

    filepath= Server.MapPath(filepath);
                    FileStream strm = new FileStream(filepath, FileMode.Open, FileAccess.Read);
    
                    byte[] fileByte = new byte[strm.Length];
                    int x = strm.Read(fileByte, 0, fileByte.Length);
    
                    Response.Clear();
                    Response.AddHeader("Accept-Header", fileByte.Length.ToString());
                    Response.AddHeader("Content-Disposition","inline; filename=" + filename);
                    Response.ContentType = "application/pdf";
                    Response.OutputStream.Write(fileByte, 0, fileByte.Length);
                    Response.Flush();
                    strm.Close();
    

    并且您的内容类型必须为“application/pdf”

        4
  •  1
  •   devio    15 年前

    尼古拉斯认为“octetstream”(没有破折号)不是已知的 MIME Type .

    我建议使用 application/pdf .

        5
  •  0
  •   PhilPursglove    15 年前

    如果你使用 response.TransmitFile / response.WriteFile ?

    TransmitFile (MSDN)
    WriteFile(MSDN)

        6
  •  0
  •   DavidGouge    15 年前

    好的,我已经将内容类型更正为application/octet stream并更改了缓存。这似乎是一个IE+SSL问题,所以我将在今晚晚些时候部署它时查明它是否有效。谢谢你的帮助。

        7
  •  -2
  •   x2. alexey    15 年前

    发现于 google 类似问题的解决:

    Response.AppendHeader('Expires', 'Sun, 17 Dec 1989 07:30:00 GMT');
    
    推荐文章