日期:2014-05-19  浏览次数:20834 次

关于二进制与数据库存储的问题
哪位高手可以提供   上传文件的时候将上传文件转换成二进制形式存储在数据库中     然后可以直接从数据库中下载二进制数据的解决方案


------解决方案--------------------
可以将二进制大对象 (BLOB) 作为二进制或字符数据写入数据库,具体视数据源的字段类型而定。若要将 BLOB 值写入数据库,请发出相应的 INSERT 或 UPDATE 语句并将 BLOB 值作为输入参数传递(请参见将存储过程用于命令)。如果 BLOB 存储为文本格式(如 SQL Server text 字段),则可将 BLOB 作为字符串参数传递。如果 BLOB 存储为二进制格式(如 SQL Server image 字段),则可将类型 byte 的数组作为二进制参数传递。

BLOB 可能相当大,因此在作为单个值写入时可能要使用大量的系统内存,从而降低应用程序的性能。若要减少写入 BLOB 值时所使用的内存量,可以按“块”将 BLOB 写入数据库。用该方法将 BLOB 写入数据库的过程具体取决于数据源的功能。有关按块将 BLOB 值写入 SQL Server 的示例,请参见将 BLOB 值写入 SQL Server 时节省资源。


以下代码示例将员工信息添加到 Northwind 数据库的 Employees 表中。员工照片将从文件中读取并添加到表中的 Photo 字段,该字段为 image 字段。

public static void AddEmployee(
string lastName,
string firstName,
string title,
DateTime hireDate,
int reportsTo,
string photoFilePath,
string connectionString)
{
byte[] photo = GetPhoto(photoFilePath);

using (SqlConnection connection = new SqlConnection(
connectionString))

SqlCommand command = new SqlCommand(
"INSERT INTO Employees (LastName, FirstName, " +
"Title, HireDate, ReportsTo, Photo) " +
"Values(@LastName, @FirstName, @Title, " +
"@HireDate, @ReportsTo, @Photo) ", connection);

command.Parameters.Add( "@LastName ",
SqlDbType.NVarChar, 20).Value = lastName;
command.Parameters.Add( "@FirstName ",
SqlDbType.NVarChar, 10).Value = firstName;
command.Parameters.Add( "@Title ",
SqlDbType.NVarChar, 30).Value = title;
command.Parameters.Add( "@HireDate ",
SqlDbType.DateTime).Value = hireDate;
command.Parameters.Add( "@ReportsTo ",
SqlDbType.Int).Value = reportsTo;

command.Parameters.Add( "@Photo ",
SqlDbType.Image, photo.Length).Value = photo;

connection.Open();
command.ExecuteNonQuery();
}
}

public static byte[] GetPhoto(string filePath)
{
FileStream stream = new FileStream(
filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);

byte[] photo = reader.ReadBytes((int)stream.Length);

reader.Close();
stream.Close();

return photo;
}