繁体   English   中英

将文件存储到SQL Server数据库/从SQL Server数据库检索文件

[英]Store/retrieve files to/from SQL Server database

我想允许用户将文件附加到项目中。 文件可以是图像,文档,文本,zip文件等。

我在数据库中创建了一个表,该表将存储文件名,扩展名,大小,有关文件的注释以及文件数据。 文件数据的列类型为VarBinary (blob)。

现在,我已经从用户那里获取了输入并将其存储在本地列表视图中(未绑定到db)。 我想在列表视图行上进行迭代,并将它们存储到数据库中。 如何将文件数据存储到BLOB列?

尝试这个

// **** Read File/Image into Byte Array from Filesystem
        public static byte[] GetPhoto(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);

            byte[] photo = br.ReadBytes((int)fs.Length);

            br.Close();
            fs.Close();

            return photo;
        }

然后调用上面的函数添加到数据库中

// **** Read Image from Filesystem and add it to the Database.
        public void AddFileDataIntoDatabase(
            string a,string b,string c, string photoFilePath)
        {

            // Read Image into Byte Array from Filesystem
            byte[] photo = GetPhoto(photoFilePath);

            // Construct INSERT Command
            SqlCommand addEmp = new SqlCommand(
                "INSERT INTO tablename ("+
                "col1,col2,Col3,Photo) "+
                "VALUES(@col1,@col2,@col3,@Photo)",_conn);

            addEmp.Parameters.Add("@col1",  SqlDbType.NVarChar, 20).Value = plastName;
            addEmp.Parameters.Add("@col2", SqlDbType.NVarChar, 10).Value = pfirstName;
            addEmp.Parameters.Add("@col3",     SqlDbType.NVarChar, 30).Value = ptitle;                
            addEmp.Parameters.Add("@Photo",     SqlDbType.Image, photo.Length).Value = photo;

            // Open the Connection and INSERT the BLOB into the Database
            _conn.Open();
            addEmp.ExecuteNonQuery();
            _conn.Close();
        }

请参考这里

SELECT * FROM OPENROWSET(BULK N'<FILEPATH>', SINGLE_BLOB) AS Contents
It'll pull in the contents of the file as varbinary.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM