下载附件

来源:互联网 发布:西门子plc vb编程入门 编辑:程序博客网 时间:2024/04/28 18:53

  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();
        }
    }