C# ASP.NET 3.5 内容-提示文件下载问题

6

我有一个存储一些文档的 SQL 数据库。

用户可以登录该应用程序,查看他们文档的列表。

在网格视图中点击下载链接按钮,我从数据库获取文件,将其写入文件系统,然后执行此代码。

    System.IO.FileInfo file = new System.IO.FileInfo(System.Configuration.ConfigurationManager.AppSettings["UploadPath"] + DocumentName);

    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Cookies.Clear();
    Response.Cache.SetCacheability(HttpCacheability.Private);
    Response.CacheControl = "private";
    Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
    Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
    Response.AppendHeader("Content-Length", file.Length.ToString());
    Response.AppendHeader("Pragma","cache");
    Response.AppendHeader("Expires", "60");
    Response.ContentType = GetContentType(file.Extension);
    Response.AppendHeader("Content-Disposition",
    "inline; " +
    "filename=\"" + file.Name + "\"; " +
    "size=" + file.Length.ToString() + "; " +
    "creation-date=" + DateTime.Now.ToString("R") + "; " +
    "modification-date=" + DateTime.Now.ToString("R") + "; " +
    "read-date=" + DateTime.Now.ToString("R"));

我的GetContentType()方法只返回我允许的文件类型,例如"application/pdf, application/msw0rd"等。
我的问题是,当文件保存时,保存的是网页本身,而不是文件系统中的文件。在谷歌浏览器中,它会在文件名后面加上.htm扩展名,我想这是因为它知道它是一个网页?
无论如何,一个很好的第一步是获得实际的文件,而不是HTML页面上的副本!
谢谢。
3个回答

9

与其使用

Response.AppendHeader("Content-Disposition", "inline; " + "filename=

不如使用

Response.AddHeader("content-disposition:", "attachment;filename=


9
你是如何发送文件的实际内容的?
我通常使用Response.TransmitFile方法,它会打开文件并将其内容发送到Response.OutputStream。

3
你是否尝试将content-disposition设置为“attachment”,而不是“inline”?我相信浏览器会提示用户打开或保存文档。
此外,你通常可以通过使用BinaryWrite方法直接将数据库中的字节流写入Response对象来绕过文件系统...这也是你可能需要研究使用HTTP处理程序而不是ASPX页面的情况,这样你就不需要担心清除响应等问题。我曾经成功地在页面上使用隐藏的iframe,然后使用Javascript将其src设置为一个HTTP处理程序,该处理程序将文档ID作为查询字符串参数。

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