我正在尝试通过 HTTPS 下载文件,它在 IE 中失败,但在 Firefox 和 Chrome 中完美运行:
aspx代码如下:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CRISIIWebApplication1.Default" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</asp:Content>
点击按钮后的代码如下:
protected void Button1_Click(object sender, EventArgs e)
{
string filename = TextBox1.Text;
string filepath = Server.MapPath(filename);
byte[] bytFile = null;
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(filepath).Length;
bytFile = br.ReadBytes((int)numBytes);
string extension = ".xlsx";
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
if (extension == ".doc")
{
Response.ContentType = "application/vnd.ms-word";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
}
else if (extension == ".docx")
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
}
else if (extension == ".xls" || extension == ".xlsx")
{
if (extension == ".xls")
{
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
}
else
{
Response.ContentType = "application/ms-excel";
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
}
}
else if (extension == ".pdf")
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
}
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytFile);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.End();
}
请帮忙
最佳答案
作为用户 SquidScareMe写道,当通过 SSL 下载 Office 文件时,您必须忽略/不要触及它们的缓存设置。
我有一个 .ashx
处理程序,它有一个片段:
// "Internet Explorer is unable to open Office documents from an SSL Web site".
// http://support.microsoft.com/kb/316431/en-us
if (!context.Request.IsSecureConnection || !isInternetExplorer(context))
{
// No cache.
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.AppendHeader(@"Pragma", @"no-cache");
}
有了这个功能:
private static bool isInternetExplorer(HttpContext context)
{
return context.Request.Browser.Browser == @"IE";
}
关于c# - 文件下载在 IE 中通过 https 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5198530/