C#上傳圖片到指定資料夾
最近寫了一段程式碼實現圖片上傳功能,設計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>");
}
}
實現的過程很簡單,程式碼也很少!要顯示圖片的話直接從資料夾路徑裡取就可以,但此方法的缺點是佔用比較大的伺服器空間.而且資料的安全和完整性也不好.最好使用的方法還是把圖片檔案轉換成檔案流的方式儲存到資料庫!