ASP.NET上傳圖片檔案
來源:互聯網
上載者:User
using System;
using System.IO;public partial class _Default : System.Web.UI.Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
if(IsPostBack)
{
Boolean fileOK = false;//定義變數判斷檔案是否為圖片
String path = Server.MapPath("~/UploadedImages/");//指定檔案儲存路徑 if (fuUpload.HasFile) //判斷控制項是否選擇檔案
{
String fileExtension = Path.GetExtension(fuUpload.FileName).ToLower();//使用該方法得到上傳檔案的副檔名
String[] allowedExtensions = {".gif", ".png", ".jpeg", ".jpg"};//定義允許上傳的副檔名 for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])//如果上傳檔案通過檢測
{
fileOK = true;//將該變數設值為true
}
}
} if (fileOK)//判斷是否通過檢測
{
try
{
if (!Directory.Exists(path))//使用Directory類的方法判斷儲存路徑目錄是否存在
{
Directory.CreateDirectory(path);//如果不存在便建立該目錄
}
fuUpload.PostedFile.SaveAs(path + fuUpload.FileName);
Label1.Text = "File uploaded!";
}
catch(Exception ex)
{
Label1.Text = "File could not be uploaded." + ex.Message;
}
}
else
{
Label1.Text = "Cannot accept files of this type.";
}
}
string strFileName = fuUpload.FileName;
}
}
HTML_Code:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fuUpload" runat="server" Height="24px" Style="z-index: 100;
left: 104px; position: absolute; top: 84px" Width="480px" />
<asp:Label ID="Label1" runat="server" Style="z-index: 103; left: 104px; position: absolute;
top: 52px" Width="476px"></asp:Label>
<asp:Button ID="btnUpload" runat="server" Height="24px" OnClick="btnUpload_Click"
Style="z-index: 102; left: 104px; position: absolute; top: 124px" Text="上傳" Width="84px" />
</div>
</form>
</body>
</html>