最近写了一段代码实现图片上传功能,设计Access数据库的时候原先把记录图片的字段类型选为OLE对象,可是实现了上传后却取不到图片显示(SQL2000数据库时可以实现,理论上用Access数据库也是差不多,但Access数据库却显不了图片),到现在也没去详查什么原因,最后为了尽早解决这个功能,改用了比较简单的方法。
该方法就是在Project里建一个名为UpPic的文件夹,把记录图片的字段类型改为文本类型,该字段只是记录上传图片的名称,而图片实质上是保存在UpPic文件夹里。
前台CODE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<input id="picFile" name="picFile" type="file" style="WIDTH: 488px; HEIGHT: 22px" runat="server">
</div>
<div>
<asp:button id="Button1" runat="server" Text="提 交" Width="75px"
onclick="Button1_Click"></asp:button>
</div>
</div>
</form>
</body>
</html>
后台CODE(Button1_Click方法):
protected void Button1_Click(object sender, EventArgs e)
{
string image = picFile.Value;
string imagecontent = "";
string exname = image.Substring(image.LastIndexOf(".") + 1).ToUpper(); //截取图片的后缀名并转为大写
if (exname == "JPG" || exname == "JPEG" || exname == "GIF" || exname == "PNG" || exname == "BMP")
{
if (picFile.PostedFile.ContentLength > 524288)
{
Response.Write("<script>alert('上传的图片大于 0.5M, 请处理图片后再上传! ')</script>");
return;
}
//用时间作为图片名
string filetime = DateTime.Now.ToString("yyyyMMddhhmmssfff"); //取得当前时间
string filename = picFile.PostedFile.FileName; //取得图片名
imagecontent = filetime + filename.Substring(filename.LastIndexOf(".")); //时间名加上图片后缀名
string strpath = Server.MapPath("") + "//UpPic//" + imagecontent; //取得将要保存图片的路径
picFile.PostedFile.SaveAs(strpath); //把图片保存在此路径中
}
else
{
Response.Write("<script>alert('上传的不是图片类型! ')</script>");
return;
}
int i = 0;
i = g2.AddProInfo(imagecontent); //调用webserver中的方法
if (i == 0)
{
Response.Write("<script>alert(' 添 加 失 败! ');window.location.href='AddProInfo.aspx'</script>");
}
else
{
Response.Write("<script>alert(' 添 加 成 功 !'); </script>");
}
}
实现的过程很简单,代码也很少!要显示图片的话直接从文件夹路径里取就可以,但此方法的缺点是占用比较大的服务器空间.而且数据的安全和完整性也不好.最好使用的方法还是把图片文件转换成文件流的方式保存到数据库!