asp.net如何将一个图片保存到sqlserver,不是图片路径 20
1个回答
展开全部
//将图片转行为二进制的方式,存储到数据库
string name = FileUpload1.PostedFile.FileName;
string type = name.Substring(name.LastIndexOf(".") + 1);
FileStream fs = File.OpenRead(name);
byte[] content = new byte[fs.Length];
fs.Read(content, 0, content.Length);
fs.Close();
//操作SQL数据库存储,请结合自己的软件
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Pooling=False;Password=");
SqlCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = "insert into Images(Image_Content) values (@content)";
cmd.CommandType = CommandType.Text;
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png")
{
SqlParameter para = cmd.Parameters.Add("@content", SqlDbType.Image);
para.Value = content;
cmd.ExecuteNonQuery();
}
//读取数据库字段,并展示图片
string imgid = Request.QueryString["imgid"];
SqlConnection conn1 = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=sa;Pooling=False;Password=");
SqlCommand cmd1 = new SqlCommand("select Image_Content from Images where Image_ID=3", conn1); //固定显示Image_ID为3的图片
conn1.Open();
SqlDataReader sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
Response.BinaryWrite((byte[])sdr["Image_Content"]);
}
Response.End();
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询