本節以新聞管理系統為例,實作新聞新增功能,包含標題、內容、圖片與附件上傳,展示 Web Forms 中檔案上傳與資料庫寫入的完整流程。
newsadd.aspx
public class newsclass {
public string Title { get; set; }
public string Contents { get; set; }
public string Img { get; set; } // 圖片檔名
public string Annex { get; set; } // 附件檔名
public string Time { get; set; } // 發布時間
}
public static void addnews(newsclass news) {
using (SqlConnection cn = dbconn.GetConnection()) {
cn.Open();
string sql = "INSERT INTO news (title, contents, img, annex, time) VALUES (@title, @contents, @img, @annex, @time)";
using (SqlCommand cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.AddWithValue("@title", news.Title);
cmd.Parameters.AddWithValue("@contents", news.Contents);
cmd.Parameters.AddWithValue("@img", news.Img);
cmd.Parameters.AddWithValue("@annex", news.Annex);
cmd.Parameters.AddWithValue("@time", news.Time);
cmd.ExecuteNonQuery();
}
}
}
protected void Button1_Click(object sender, EventArgs e) {
var news = new newsclass {
Title = TextBox1.Text.Trim(),
Contents = TextBox2.Text.Trim(),
Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
};
// 處理圖片上傳
if (FileUpload1.HasFile) {
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName;
string savePath = Server.MapPath("../upfile/" + fileName);
FileUpload1.SaveAs(savePath);
news.Img = fileName; // 僅儲存檔名,路徑由系統統一管理
}
// 處理附件上傳
if (FileUpload2.HasFile) {
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload2.FileName;
string savePath = Server.MapPath("../upfile/" + fileName);
FileUpload2.SaveAs(savePath);
news.Annex = fileName;
}
newschuli.addnews(news);
Response.Redirect("NewsCategoriesManager.aspx");
}

| 議題 | 建議做法 |
|---|---|
| 檔名衝突 | 時間戳 + GUID + 原始副檔名(如 20240115103000_a1b2c3.jpg) |
| 副檔名驗證 | 白名單驗證(.jpg/.png/.pdf/.docx),拒絕 .exe/.asp/.php 等執行檔 |
| MIME 類型二次驗證 | 讀取檔案 Header 驗證真實格式,防止偽裝副檔名 |
| 檔案大小限制 | Web.config maxRequestLength + 後端 ContentLength 檢查 |
| 儲存路徑 | 網站根目錄外的專用資料夾,配合虛擬目錄映射,避免直接腳本執行 |
| 資料庫儲存 | 僅儲存相對路徑/檔名,不儲存絕對路徑,利於遷移 |
若需支援超大檔案(>100MB),建議採用:
本節實作新聞新增與雙檔案(圖片/附件)上傳功能,展示 FileUpload 控制項搭配參數化查詢的標準用法。生產環境請務必加強檔案驗證、儲存安全與錯誤處理,必要時引入雲端儲存(Azure Blob/AWS S3)分擔伺服器負載。