2014/09/24

ASP.Net FileUpLoad

Layout:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo1.aspx.cs" Inherits="Demo.Demo1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpLoadDemo" runat="server"/><br />
        <asp:Button ID="ButtonSubmit" runat="server" Text="提交"  OnClick="ButtonSubmit_Click"/>
    </div>
        
    </form>
</body>
</html>

Code:
using System;

namespace Demo
{
    public partial class Demo1 : System.Web.UI.Page
    {
        

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            //上傳的資料夾路徑
            string folderPath = Server.MapPath("~/images/");

            //判斷FileUpLoad有沒有檔案
            if (FileUpLoadDemo.HasFile)
            {
             //取得上傳的檔案名稱
                string fileName = FileUpLoadDemo.FileName;
                //取得檔案附檔名
                string extension = System.IO.Path.GetExtension(fileName);

                //是否為jpg檔案
                if (extension.Equals(".jpg"))
                {
                 //將檔案上傳到資料夾路徑
                    FileUpLoadDemo.SaveAs(folderPath + fileName);
                    Response.Write("&lt;script&gt;alert('上傳成功');&lt;/script&gt;");
                }
                else
                    Response.Write("&lt;script&gt;alert('檔案不符合上傳條件');&lt;/script&gt;");
            }
            else
                Response.Write("&lt;script&gt;alert('您讓未選擇檔案');&lt;/script&gt;");
        }

    }
}



執行畫面:




上傳前:




上傳後:








參考資料:
http://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.fileupload(v=vs.110).aspx