[英]Adding image to database along with other fields in webforms asp.net
我有一个有列的学生表
id 主键、名字、姓氏、图片。 图片数据类型是 varbinary(MAX)
我正在使用 ASP.NET 中的 WebForms。
我有这个存储过程。
create procedure spAddStudents
(
@id int,
@firstname nvarchar(50),
@lastname nvarchar(50),
@picture varbinary(MAX)
)
as
Begin
insert into students
values (@id, @firstname, @lastname,@picture)
End
在网络表单中我写了这段代码
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filepath = "Images/" + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + filename);
SqlCommand cmd = new SqlCommand("spAddStudent",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@firstname", txtFirstName.Text);
cmd.Parameters.AddWithValue("@lastname", txtLastName.Text);
cmd.Parameters.AddWithValue("@picture",filepath);
con.Open();
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
lblMessage.Text = "Record inserted successfully";
}
}
}
当我在存储过程中将图像作为图片的数据类型时,我在 cmd.executeNonQuery() 行收到此错误
操作数类型冲突:nvarchar 与图像不兼容
当我在存储过程中将 varbinary(max) 作为图片的数据类型时,我收到此错误
不允许从数据类型 nvarchar 到 varbinary(max) 的隐式转换。 使用 CONVERT function 运行此查询。
目前,您正在尝试将硬盘驱动器上文件的路径(字符串)插入 varbinary 字段,这就是您收到此错误的原因。 而是跳过将文件写入硬盘驱动器,将字节作为数组获取,然后将其写入数据库字段。
MemoryStream uploadstream = new MemoryStream();
HttpPostedFile.InputStream.CopyTo(uploadstream);
var picturearray = uploadstream.ToArray();
List<SqlParameter> Parameters = new List<SqlParameter>();
Parameters.Add(new SqlParameter("picture", picturearray ));
此代码使用“图像”作为数据库表上的类型。 它也可以与 Varbinary(MAX) 一起使用 Parameters.AddWithValue(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.