我用图像上传制作了注册表格,图像之外的所有文本框值都上传到了SQL Server中。我写了下面显示的代码并对其进行了测试,但是它不存储任何图像。
但是当我删除图像并仅添加其他值时,它将插入数据库中而没有任何错误。
但是带有图片,它显示了一个错误:
“无法保存图书记录”
图像列的类型为varbinary(MAX)
。
protected void Button1_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filePath = string.Empty;
Byte[] bytes;
FileStream fs;
BinaryReader br;
SqlCommand cmd = new SqlCommand("InsertBookDetails_Sp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@book_num", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@BookName", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("@Publisher", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("@Price", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("@Author", TextBox6.Text.Trim());
try
{
if (FileUpload1.HasFile)
{
fileName = FileUpload1.FileName;
filePath = Server.MapPath("pth/" + System.Guid.NewGuid() + fileName);
FileUpload1.SaveAs(filePath);
fs = new FileStream(filePath, FileMode.Open,FileAccess.Read);
br = new BinaryReader(fs);
bytes = br.ReadBytes(Convert.ToInt32(fs.Length));
br.Close();
fs.Close();
cmd.Parameters.AddWithValue("@BookPic", bytes);
}
con.Open();
cmd.ExecuteNonQuery();
lblStatus.Text = "Book Record saved successfully";
lblStatus.ForeColor = Color.Green;
}
catch (Exception)
{
lblStatus.Text = "Book Record could not be saved";
lblStatus.ForeColor = Color.Red;
}
finally
{
con.Close();
cmd.Dispose();
fileName = null;
filePath = null;
fs = null;
br = null;
}
}
答案 0 :(得分:1)
使用此代码
byte[] fileBytes= FileUpload1.FileBytes;
cmd.Parameters.AddWithValue("@BookPic", fileBytes);
并删除FileStream方法