ASP.NET从数据库中下载文件

private string Download(string sID)
    {  

        string sql = "select FileName,File FROM 文件列表 where FileID = " + sID;
        SqlConnection con = ZFilesList.ZOpenConnecttion();
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
        {

            string sFileName = reader["FileName"].ToString();
            Response.ClearHeaders();
            Response.Clear();
            Response.Expires = 0;
            Response.Buffer = true;
            Response.Charset = "gb2312";
            //把 attachment 改为 online 则在线打开
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" +Server.UrlEncode(sFileName) + "\"");//很重要不然显示出来的是乱码
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            
            Page.EnableViewState = false;
            string[] keyValue = sFileName.Split(".".ToCharArray());
            if(keyValue.Length>=2)
            {
                string type = (string)((keyValue[keyValue.Length - 1]).ToString());
                Response.ContentType = GetResponseContentType(type); 
            }
            byte[] bt = (byte[])reader["File"];
            Response.OutputStream.Write(bt, 0, bt.Length);
        }

        reader.Close();
        reader.Dispose();
        cmd.Dispose();
    }
        public string GetResponseContentType(string fileType)
        {
            string type;
            switch (fileType)
            {
                case "doc": type = "application/vnd.ms-word"; break;
                case "jpg": type = "image/jpeg"; break;
                case "txt": type = "application/vnd.ms-word"; break;
                case "tif||tiff": type = "text/plain"; break;
                case "gif": type = "image/gif"; break;
                case "bmp": type = "image/bmp"; break;
                case "swf": type = "application/x-shockwave-flash"; break;
                case "zip": type = "application/zip"; break;
                case "sql": type = "application/vnd.ms-word"; break;
                case "dwg": type = "application/autocad"; break;
                case "pdf": type = "application/pdf"; break;
                case "ppt": type = "appication/powerpoint"; break;
                default: type = "text/html"; break;
            }
            return type;
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值