我有一个数据库列'images'可以保存二进制数据,由于某种原因图像不想上传。它可以解决代码中的任何异常或错误:
这里是代码的摘录
protected void BtnAdd_Click(object sender, EventArgs e)
{
string imgpath = FileUploadImage.FileName.ToString();
DBConnectivity.Add(imgpath);
}
here is the DBCoectivity Class:
public static void Add(string imgpath)
{
byte[] imgbt = null;
FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
BinaryReader BR = new BinaryReader(fstream);
imgbt = BR.ReadBytes((int)fstream.Length);
SqlConnection myConnection = GetConnection();
string myQuery = "INSERT INTO images( imagePath) VALUES ( @IMG )";
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.Parameters.Add(new SqlParameter("@IMG",imgbt));
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
答案 0 :(得分:1)
这段代码对我有用:
byte[] imgbt = null;
if (FileUploadImage.HasFile)
{
Stream photoStream = FileUploadImage.PostedFile.InputStream;
imgbt = new byte[FileUploadImage.PostedFile.ContentLength];
photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength);
}
此外,您正在将图像名称(拼写错误作为参数添加到Add方法,错误选择变量名称,因为它不是路径)插入数据库,而不是二进制数据。它应该是:
string myQuery = "INSERT INTO images(imgbt) VALUES (@IMG)";
这是一个示例教程,可以更好地解释它: