---
# System prepended metadata

title: 筆記_使用HTML方式上傳檔案
tags: [.NET, 檔案上傳, web form]

---

# 筆記_使用HTML方式上傳檔案
----
###### tags: `web form` `.NET` `檔案上傳`

---

引用:


![](https://i.imgur.com/RLsDZIO.png)

![](https://i.imgur.com/r0DdDq6.png)

![](https://i.imgur.com/F3NhzqN.png)

![](https://i.imgur.com/6ow5wtX.png)

![](https://i.imgur.com/lXghHyd.png)

![](https://i.imgur.com/KvrW3hq.png)

![](https://i.imgur.com/CMT162D.png)

![](https://i.imgur.com/DE7HISk.png)


使用的Code

```csharp
protected void ServeSideEvent(object sender, EventArgs e)
{
    string path = Server.MapPath("~/Upload");
    string absolutePath;
    string ext;
    string str = "";
    int fileSize = 20971520;

    if (System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
    
    // 查到的功能 還不會用
    //Response.Write(Request.Files.AllKeys + "<br />");
    // Response.Write(Request.Files.Keys + "<br />");
    /*
    HttpPostedFile file = Request.Files["File1"];
    if (file != null && file.ContentLength > 0)
    {
        Response.Write(file);
    }
    Response.Write(file);
    */

    //Request.Files = Context.Request.Files
    for (int i = 0; i < Request.Files.Count; i++) // 無法使用控制項功能
    {
        if (Request.Files[i].FileName == "" || Request.Files[i].ContentLength == 0)
        {
            Response.Write("請選擇圖片");
        }
        else
        {
            HttpPostedFile file = Request.Files[i];
            ext = System.IO.Path.GetExtension(file.FileName).ToLower();

            if (ext == ".jpeg" || ext == ".png" || ext == ".jpg")
            {
                if (file.ContentLength <= fileSize)
                {
                    absolutePath = path + "\\" + file.FileName;
                    if (!System.IO.File.Exists(absolutePath))
                    {
                        file.SaveAs(absolutePath);
                        //Response.Write(absolutePath);
                    }
                    else
                    {
                        str += file.FileName + "上傳檔案名稱重複<br />";
                    }
                }
                else
                {
                    str += file.FileName + "上傳檔案超過20MB<br />";
                }
            }
            else
            {
                str += file.FileName + "上傳檔案不符合格式<br />";
            }
        }
    }
    Label1.Text = "程式結束";
    Label2.Text = str;
    //Response.Write(str);
}
```








