每当我访问我的 ashx,例如 download.ashx?id=18 时,它都会获取文件,但是当保存对话框弹出时,它要我保存 download.ashx 而不是我存储在数据库中的文件(让说 mypdf.pdf)如果你打开文件下载,它会在 Visual Studio 中打开,并没有真正显示任何有用的东西。是什么原因造成的,我在很多浏览器和很多机器上都试过了,结果都一样?
谢谢
string id = ctx.Request.QueryString["id"];
string name = null;
string mime = null;
SqlConnection con = new SqlConnection(CONN);
SqlCommand cmd = new SqlCommand("DownloadActivityFile", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@aid", id);
byte[] afile = null;
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
mime = reader["ActivityFileMIME"].ToString();
ctx.Response.ContentType = mime;
afile = (byte[])reader["ActivityFile"];
name = reader["ActivityFileName"].ToString();
}
ctx.Response.Buffer = false;
ctx.Response.ContentType = mime;
ctx.Response.AddHeader("content-disposition", string.Format("attachment; {0}", name));
ctx.Response.Clear();
ctx.Response.BinaryWrite(afile);
ctx.Response.End();
}
catch (Exception e)
{
ctx.Response.Write(e.ToString());
}
finally
{
con.Close();
}
请您参考如下方法:
你需要设置Content-Disposition: attachment; filename=\"{0}\" header 。
请注意 filename=,以及名称周围的引号。
