图片上传并保存到数据库以及显示图片
此处是用保存图片相对路径的方法,上传图片。
1. 首先创建数据库表:
create table images
(
image_ID int primary key identity,
image_Wpath varchar(50)not null
)
--image_Wpath用来保存图片的相对路径
2. 页面:
Add a new folder named images, it will be used in the following steps.
上传图片:一个UploadFile控件,id=“inputFile”,一个 Button控件,id="btnUpload". lblMessage显示提示信息。
显示图片:txtImageID 用来输入想要现实的图片ID,lblPath显示所选图片的绝对路径。btnShow按钮
效果图如下所示。
3. 后台代码(1)图片上传:
protected void btnUpload_Click(object sender, EventArgs e)
{
string fileName = inputFile.FileName;//get the file name
string type = fileName.Substring(name.LastIndexOf(".") + 1); //get the file type
//string fileExt= System.IO.Path.GetExtension(inputFile.FileName); //获取文件后缀名 也可以
//if(type == ".jpg" || type == ".gif" || type == ".bmp" || type == ".png")
string ipath = Server.MapPath("images") + "\\" + fileName; //获取文件路径
string wpath = "images\\" + fileName; //设置文件保存相对路径 (我们存放图片的文件夹名)
if (type == "jpg" || type == "gif" || type == "bmp" || type == "png")
{
inputFile.SaveAs(ipath);
int j = InsertToImages(wpath); //自定义方法,保存图片至数据库
if (j > 0)
{
lblMessage.Text = "Saved!";
}
else
{
lblMessage.Text = "Failed to save!";
}
}
else
{
lblMessage.Text = "The file format is not correct, please change another one!";
}
}
/// <summary>
/// save the image in db table
/// </summary>
/// <param name="wpath">wpath</param>
/// <returns>int i</returns>
private int InsertToImages(string wpath)
{
SqlConnection conn = new SqlConnection(@"Data Source=stkwx028\sqlexpress;Initial Catalog=BBS;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = @"INSERT INTO images(image_Wpath)
VALUES(@wpath)";
cmd.Parameters.AddWithValue("@wpath", wpath);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}
后台代码(2)显示图片:
protected void btnShow_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt32(txtPathID.Text);
string wpath = GetWpathByID(imageid);
Image1.ImageUrl = wpath;
lblPath.Text = wpath;
}
/// <summary>
/// Get Wpath by imageID
/// </summary>
/// <param name="imageID">imageID</param>
/// <returns>string wpath</returns>
private string GetWpathByID(int imageID)
{
SqlConnection conn = new SqlConnection(@"Data Source=stkwx028\sqlexpress;Initial Catalog=BBS;Integrated Security=True");
string wpath = "";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = @"SELECT * FROM images
WHERE image_ID=@image_ID";
cmd.Parameters.AddWithValue("@image_ID", imageID);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
wpath=sdr["image_Wpath"].ToString();
}
conn.Close();
return wpath;
}