protected void Page_Load(object sender, EventArgs e)
{
string AttachmentID = "";
try
{
AttachmentID = Request.QueryString["AttachmentID"] == null ? "" : Request.QueryString["AttachmentID"].ToString();
if ("" == AttachmentID)
{
Response.Close();
}
else
{
DataTable m_Dtl = new DataTable();
BLL_TBAbsenceAttachment attachment = new BLL_TBAbsenceAttachment();
m_Dtl = attachment.GetAttachmentByID(AttachmentID);
if (m_Dtl.Rows.Count > 0)
{
/*方法二:空格被替换成"+"了*/
string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(m_Dtl.Rows[0]["FileName"].ToString()));
FileName = FileName.Replace("+", " ");//空格被替换成"+"了 反替换
Response.AddHeader("Content-Disposition", "attachment; filename=" + @FileName);
Response.Charset = "gb2312";
Response.ContentType = "application/octet-stream";
Response.BinaryWrite((byte[])m_Dtl.Rows[0]["Content"]);
Response.Flush();
/*原始方法
Response.AddHeader("Content-Disposition", "attachment; filename=" + m_Dtl.Rows[0]["AttachmentName"].ToString());
Response.Charset = "gb2312";
Response.ContentType=m_Dtl.Rows[0]["AttachmentContentType"].ToString();
Response.BinaryWrite((byte[])m_Dtl.Rows[0]["AttachmentContent"]);
Response.Flush();*/
}
else
{
Response.Close();
}
}
}
catch (Exception)
{
throw new Exception();
}
}
本文介绍了一个改进的ASP.NET文件下载方法,通过处理文件名中的空格并设置正确的HTTP头来确保文件能正确下载到客户端。该方法还包含了错误处理以确保稳定性。

被折叠的 条评论
为什么被折叠?



