把文件以二进制形式(Image类型)存入数据库和从数据库中读取

1、存入数据库

 

       int DocLen = FileUpload1.PostedFile.ContentLength;
        byte[] Docbuffer = new byte[DocLen];
        Stream objStream = FileUpload1.PostedFile.InputStream;
        objStream.Read(Docbuffer, 0, DocLen);

        SqlConnection myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["BaseConnectionString"].ConnectionString);
        SqlCommand mycmd = new SqlCommand();
        mycmd.Connection = myconn;
        myconn.Open();
        mycmd.CommandText = "INSERT INTO Temp1(FileType,FileSize,FileContent) VALUES ('" + FileUpload1.FileName.ToString().Substring(FileUpload1.FileName.Length - 4) + "','" + DocLen.ToString() + "',@FileContent)";
        SqlParameter paramData = new SqlParameter("@FileContent", SqlDbType.Image);
        paramData.Value = Docbuffer;
        mycmd.Parameters.Add(paramData);
        mycmd.ExecuteNonQuery();
        myconn.Close();

 

2、从数据库中读取

SqlCommand mycmd= new SqlCommand("SELECT FileType,FileSize,FileContent FROM Temp1 WHERE ID = 1", myconn);
        SqlDataReader mydr = mycmd.ExecuteReader();
        if (mydr.Read())
        {
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString() + HttpUtility.UrlEncode( + mydr["FileType"].ToString(), System.Text.Encoding.UTF8));

            byte[] buffer = new Byte[10240];
            long datalen = mydr.GetBytes(2, 0, null, 0, 0);

            long curPos = 0;
            long readsize = 0;
            readsize = mydr.GetBytes(2, curPos, buffer, 0, 10240);
            while (readsize == 10240)
            {
                curPos += readsize;
                Response.BinaryWrite(buffer);
                Response.Flush();
                readsize = mydr.GetBytes(2, curPos, buffer, 0, 10240);
            }
            byte[] rBuf = new Byte[readsize];
            mydr.GetBytes(2, curPos, rBuf, 0, (int)readsize);
            Response.BinaryWrite(rBuf);
            Response.Flush();
        }
        mydr.Close();

转载于:https://www.cnblogs.com/nextsoft/articles/1270451.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值