在ASP.NET中,将图片存储到数据库并读取显示是一个常见的需求,本文将详细介绍两种主要方法:上传图片的相对路径和以二进制流的方式存储图片。

一、上传图片的相对路径
这种方法相对简单,只需将图片的相对路径存入数据库,然后在需要显示图片时,通过相对路径读取。
1. 数据库设计
表结构如下:
| Image_ID | int identity(1,1) primary key not null |
| Image_Wpath | varchar(50) null |
2. 页面设计
<form id="form1" runat="server" style="font-size:12px;" enctype="multipart/form-data">
备注:<asp:TextBox ID="markname" runat="server"></asp:TextBox>
上传:<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="return checkClint()" Text="上传" onclick="Button1_Click" />
</form>
3. 代码实现
上传按钮事件:
protected void Button1_Click(object sender, EventArgs e)
{
string name = FileUpload1.PostedFile.FileName;
string type = name.Substring(name.LastIndexOf(".") + 1);
string ipath = Server.MapPath("Image") + "\\" + name;
string wpath = "Image\\" + name;
string query1 = "insert into Images values('" + wpath + "')";
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png")
{
FileUpload1.SaveAs(ipath);
sqlHelper.ExecterNonQuery(query1);
}
}
读取显示按钮事件:

protected void Button2_Click(object sender, EventArgs e)
{
string query2 = "select * from Images where Image_ID=" + Convert.ToInt32(TextBox1.Text);
SqlDataReader sdr = sqlHelper.GetReader(query2);
string wpath2 = "";
while (sdr.Read())
{
wpath2 = sdr[1].ToString();
}
sdr.Close();
Image1.ImageUrl = wpath2;
Label1.Text = wpath2;
}
二、以二进制流的方式存储图片
这种方法更为灵活,适用于交互性较强的页面,如校友录等,图片以二进制形式存储在数据库中,读取时也以二进制流的形式读取。
1. 数据库设计
表结构如下:
| Image_ID | int identity(1,1) primary key not null |
| Image_Content | image null |
2. 页面设计
与第一种方法相同。
3. 代码实现
上传按钮事件:

protected void Button1_Click(object sender, EventArgs e)
{
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();
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;
SqlParameter para = new SqlParameter("@content", SqlDbType.Image);
para.Value = content;
cmd.Parameters.Add(para);
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png")
{
cmd.ExecuteNonQuery();
}
}
读取显示按钮事件:
protected void Button2_Click(object sender, EventArgs e)
{
string query2 = "select * from Images where Image_ID=" + Convert.ToInt32(TextBox1.Text);
SqlDataReader sdr = sqlHelper.GetReader(query2);
byte[] content = null;
while (sdr.Read())
{
content = (byte[])sdr[1];
}
sdr.Close();
Response.BinaryWrite(content);
}
三、相关问题与解答
Q1: 如何确保图片文件在上传过程中不丢失数据?
A1: 确保使用合适的文件流读取方式,并在读取完成后及时关闭文件流,可以使用事务来确保数据库操作的原子性,避免部分数据写入导致的数据不一致问题。
Q2: 如何处理大文件上传时的内存溢出问题?
A2: 对于大文件上传,可以考虑分块上传或使用流式处理方式,避免一次性将整个文件读入内存,可以在web.config中增加请求大小限制,防止恶意的大文件上传攻击。
以上就是关于“asp.net 图片 数据库”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!