Mssql数据库中存储doc,pdf,exe,iso等电影文件和大文件上传

一、大文件上传

文件上传用vs自带的控件:FileUpLoad,默认上传大小4m。

<asp:FileUpload ID="FileUpload1" runat="server" />

修改配置文件让FileUpload上传大于1GB的文件。

在system.web标签中添加httpRuntime,其中maxRequestLength的单位为KB

    <httpRuntime maxRequestLength="5242880"/> 最大5G

 二、存贮数据

        if (FileUpload1.HasFile)
        {
            using (SqlConnection con = new SqlConnection("data source=.;database=test;uid=sa;pwd=123"))
            {
                FileUpload1.SaveAs(Server.MapPath("~/f/")+FileUpload1.FileName);
                byte[] buffer = new byte[FileUpload1.PostedFile.ContentLength];
                Stream s = FileUpload1.PostedFile.InputStream;
                s.Read(buffer, 0, buffer.Length);
                SqlCommand cmd = new SqlCommand("insert into t(msg,name) values(@msg,@name)", con);
                cmd.Parameters.Add("@msg", SqlDbType.VarBinary).Value = buffer;
                cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = FileUpload1.FileName;
                con.Open();
                cmd.CommandTimeout = 40;
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

三、从数据库中读出数据并存为文件

        using (SqlConnection con = new SqlConnection("data source=.;database=test;uid=sa;pwd=123"))
        {
            SqlCommand cmd = new SqlCommand("select * from t where id="+TextBox1.Text, con);
            con.Open();
            cmd.CommandTimeout = 40;
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                byte[] bufer = (byte[])dr["msg"];
                string path=Server.MapPath("~/o/") + dr["name"].ToString();
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                FileStream fs = new FileStream(path, FileMode.Create);
                fs.Write(bufer, 0, bufer.Length);

                fs.Close();
            }
            dr.Close();
            con.Close();
        }

创建数据表脚本

View Code
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[t]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[t](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [msg] [varbinary](max) NULL,
    [ex] [varchar](10) NULL,
    [name] [varchar](50) NULL
) ON [PRIMARY]
END

 

源码下载

 

posted @ 2012-04-01 16:34  Xingsoft  阅读(1544)  评论(0编辑  收藏  举报