1. 程式人生 > >Asp.net中用FileUpload控制元件上傳檔案

Asp.net中用FileUpload控制元件上傳檔案

後臺程式碼:
protected void Button1_Click(object sender, EventArgs e)
        {
string upTempFileBasePath = this.MapPath(@"~/Member/UserUpLoad/TempUpLoadFiles");
string uploaFileFormat = "|.jpg|.gif|";         //圖片的格式也要在配置檔案內appSettings節點上配置
string upFileName = Tools.CreateFileName();     //通過一個方法獲得隨機的檔名
string FileExtension = Path.GetExtension(UploadPhoto.FileName).ToString().Trim(); //取得上傳檔案的字尾名,帶".",字尾名存在才有必要上傳檔案
string upSaveTempFilePath = upTempFileBasePath + "/" + upFileName + FileExtension;    //上傳檔案時的路徑

if (uploaFileFormat.IndexOf(FileExtension.ToLower()) <= 0)
{
                            Tools.ShowMessage(this.Page, "請上傳jpg或gif格式的圖片檔案!");
                            return;
}
if (UploadPhoto.PostedFile.ContentLength > 153600)
{
                            Tools.ShowMessage(this.Page, "請上傳小於150K的圖片檔案!");   //上傳檔案的大小(位元組)。
                            return;
}
UploadPhoto.SaveAs(upSaveTempFilePath);     //進行儲存上傳檔案
}


前臺程式碼:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>上傳檔案</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="UploadPhoto" runat="server" />
            <asp:Button ID="btnUpLoadFile" runat="server" Text="確定上傳" onclick="btnUpLoadFile_Click" />
        </div>
    </form>
</body>
</html>

要引用: using System.IO


此方法可以判斷檔案的上傳型別和檔案大小