1.编程实现一个简单的图片管理网站
在SQL Server数据库中创建一名为photodb的数据库,并创建photo表,并自行添加部分测试数据:
photo表,新闻信息
字段名称 | 类型 | 长度 | 是否为主键 | 外键 | 说明 |
photoId | int | 4 | 是 |
| 自动增1 |
photoPath | varchar | 200 |
|
| 照片路径 |
photoTitle | varchar | 200 |
|
| 照片标题 |
|
|
|
|
|
|
1 点击“上传”按钮,将用户选择的图片文件上传至服务器网站目录下的photo子目录下,名字不要重复,建议根据时间命名文件。并且将该图片的相对路径以及照片标题信息保存到数据库中。
2 钮,将所有的照片从数据库中取出来,将其以图片的样式显示在按钮下面指定的位置,要求每行显示5张照片,可以使用table进行布局
string connstr = @"data source=MSY;database=photodb;Integrated Security=true"//数据库连接代码
protected void Button1_Click(object sender, EventArgs e)//实现上传功能的代码
{int intCount;
if (Application["COUNT"] == null)
{
Application.Lock();
intCount = 1;
Application["COUNT"] = intCount;
Application.UnLock();
}
else
{
Application.Lock();
intCount = Convert.ToInt32(Application["COUNT"].ToString()) + 1;
Application["COUNT"] = intCount;
Application.UnLock();
}
if (FileUpload1.HasFile)
{
try
{
if (FileUpload1.PostedFile != null)
{
string fileName = FileUpload1.FileName;
string filePath = "~/Photo/" + fileName;
FileUpload1.SaveAs(filePath);
}
}
catch
{
Label1.Text = "";
}
}
SqlConnection conn = new SqlConnection(connstr);
string file = FileUpload1.FileName;
string strlink = "Photo/" + file;
string fPath = Server.MapPath("Photo/") + file;
FileUpload1.PostedFile.SaveAs(fPath);
string sql = "insert into Photo(PhotoId,PhotoPath,Phototitle) " + " values({0},'{1}','{2}')";
sql = string.Format(sql, intCount, strlink, file);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
Response.Write("<script language='javascript'> alert('提交成功!');</script>");
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connstr);
string sql = "select * from Photo";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds); int j = 1;
string strBody = "";
if (j % 5 == 0) strBody += "<tr>";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string str = @"<td align='center'><img src='{0}' width='130' height='110'/></td> ";
str = string.Format(str, ds.Tables[0].Rows[i]["PhotoPath"]);
strBody += str;
if (j % 5 == 0) strBody += "</tr>"; j++;
}
string strTble = "<table width='100%' border='0' cellspacing='0' cellpadding='0'>" + "<tr>";
strTble += strBody;
strTble += "</tr></table>";
Label2.Text = strTble;
}