简单的图片上传和图片浏览代码
简单的图片上传和图片浏览代码
图片保存在服务器上有两种方式,一种是保存在数据库当中,一种是以为文件的形式保存在网站某个目录下面,不过此目录对web用户具有写的权限,保存在数据库当中是以二进制式的形式保存,是文件流的方式读出来,如果在开发WinForm程序很流这种方法,不过在Web保存在文件夹下面比较好,把文件名保存在数据库当中
下面贴一段以二字制方式保存在数据当中的代码
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
byte[] content =FileUpload1.FileBytes;
SqlConnection Connection = new SqlConnection(@"Data Source=COMPUTER\SQLEXPRESS;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa");
Connection.Open();
SqlCommand Command = Connection.CreateCommand();
Command.CommandText = "insert into images(image,contentType) values(@image,@contentType)";
Command.CommandType = CommandType.Text;
Command.Parameters.Add("@image", SqlDbType.Image).Value = content;
Command.Parameters.Add("@contentType", SqlDbType.NVarChar).Value = GetContentType(new FileInfo(FileUpload1.FileName).Extension.Remove(0, 1));
if (Command.ExecuteNonQuery() == 1)
{
Response.Write("<script type='text/javascript'>alert('添加成功');</script>");
}
}
}
private string GetContentType(string extension)
{
string type="jpeg";
if(extension=="jpg")
{
type="jpeg";
}
else
{
type=extension;
}
return "image/"+type;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
try
{
SqlConnection connection = new SqlConnection(@"Data Source=COMPUTER\SQLEXPRESS;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa");
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "select * from images id=@id"; //注明没加id参数
command.CommandType = CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Response.ContentType = reader["contentType"].ToString();
Response.BinaryWrite((byte[])reader["image"]);
}
Response.End();
connection.Close();
}
catch
{
Response.End();
}
}
上面代码估计实际用处不大,所以也没写清楚
下面贴段代码演示一个添加保存浏览图片在一个页面,代码先行
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
string strconn = @"Data Source=COMPUTER\SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=sa";
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection Connection = new SqlConnection(strconn))
{
SqlCommand Command = Connection.CreateCommand();
Command.CommandText = "select * from images";
Command.CommandType = CommandType.Text;
Connection.Open();
SqlDataReader reader= Command.ExecuteReader();
DataList1.DataSource = reader;
DataList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss"); //格式化时间
string extension = new FileInfo(FileUpload1.FileName).Extension;
fileName = fileName + extension;
using (SqlConnection Connection = new SqlConnection(strconn))
{
SqlCommand Command = Connection.CreateCommand();
Command.CommandText = "insert into images(filename,description,datetime) values(@filename,@description,'" + DateTime.Now + "')";
Command.CommandType = CommandType.Text;
Command.Parameters.Add("@filename", SqlDbType.NChar).Value = fileName;
Command.Parameters.Add("@description", SqlDbType.NChar).Value = TextBox1.Text;
try
{
Connection.Open();
if (Command.ExecuteNonQuery() == 1)
{
FileUpload1.SaveAs(MapPath("~/upload/")+fileName);
Label1.Text ="添加成功";
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
此处使用了DataList控制来显示图片.绑定图片的代码
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
<div id="show">
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal"
RepeatColumns="3">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# (Request.ApplicationPath+("/upload/")+Eval("filename")).Trim()%>'
Width="100px" Height="100px" />
<br />
<asp:Label ID="Label2" runat="server" Text='<%#Eval("description")%>'></asp:Label>
</ItemTemplate>
</asp:DataList>
</div>
大家看到这段代码没ImageUrl='<%# (Request.ApplicationPath+("/upload/")+Eval("filename")).Trim()%>'
这个用来读取图片的地址 ,图处名最后用当时的时间命名
再上一张图了
Copy Right By Robo_zou