300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 图片上传并保存到数据库以及显示图片

图片上传并保存到数据库以及显示图片

时间:2023-08-30 02:32:10

相关推荐

图片上传并保存到数据库以及显示图片

图片上传并保存到数据库以及显示图片

此处是用保存图片相对路径的方法,上传图片。

1. 首先创建数据库表:

create table images

(

image_ID int primary key identity,

image_Wpath varchar(50)not null

)

--image_Wpath用来保存图片的相对路径

2. 页面:

Add a new folder namedimages, 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;

mandText = @"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;

mandText = @"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;

}

Be the change you want to see in the world.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。