我正在从 ms sql server 图像字段中提取数据。字节数组是这样形成的
public byte[] saveImageBlob(string number)
{
string strSql = "select pic from emp where number like '" + number + "'";
SqlCommand cmd = new SqlCommand(strSql, conn);
SqlDataReader MyReader = cmd.ExecuteReader();
if (MyReader.Read())
{
byte[] m_MyImage = (byte[])MyReader["pic"];
return m_MyImage;
}
return null;
}
然后我在 page_load 函数中调用该数组并将其放入文件流中,如下所示
Employee emp = new Employee();
emp.getEmployee(Request.QueryString["user"]);
string file_name = System.AppDomain.CurrentDomain.BaseDirectory + "/img/" + emp.Number.ToString() + ".bmp";
System.IO.FileStream _FileStream = new System.IO.FileStream(file_name, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(emp.Picture, 0, emp.Picture.Length);
_FileStream.Close();
employee 类除了在 page_load 和我的数据库类之间传递数据之外什么也不做。
文件以正确的名称保存在正确的位置,并且大小看起来正确。 但我无法打开它或查看图片。文件已损坏。
客户告诉我sql server中的图像字段包含BMP图像。
我在这里有点迷失,有人有使用 mssql blob 的经验吗?
有什么方法可以查看数据库中的图像/blob 字段是否已损坏?
我的代码中是否遗漏了一些重要的东西?
此致,ssg。
最佳答案
首先,停止在代码中进行 SQL 注入(inject)。请立即停止,检查整个项目,并使用正确的参数替换所有构建动态 SQL 的地方:
string strSql = "select pic from emp where number like @number";
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.Parameters.Add ("@number", SqlDbType.Varchar, 8000);
cmd.Parameters["@number"].Value = number;
阅读How Data Access Code Affects Database Performance关于如何正确使用参数。
其次,使用正确的谓词来定位数据。不需要LIKE
。使用=
:
string strSql = "select pic from emp where number = @number";
现在,你的问题是:为什么要首先保存图像,为什么不直接使用数据库中的图像?请参阅Download and Upload images from SQL Server via ASP.Net MVC示例使用 SQL Server BLOB 以高效的流式传输方式作为媒体存储,不使用内存阵列副本中的完整图像大小分配,也不使用中间文件。
关于c# - 使用 System.IO.FileStream 将字节数组保存为图像时无法看到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8481323/