| 方式 | 控制項/物件 | 取得檔名 | 判斷是否有檔案 | 儲存方法 | 封裝程度 |
|---|---|---|---|---|---|
| 1. Web 控制項 | FileUpload |
FileUpload1.FileName (僅檔名) |
FileUpload1.HasFile |
SaveAs(path) |
最高,最方便 |
| 2. HTML 伺服器控制項 | HtmlInputFile (runat="server") |
file1.PostedFile.FileName (IE 含完整路徑,Chrome 僅檔名) |
file1.PostedFile.ContentLength > 0 |
PostedFile.SaveAs(path) |
中等 |
| 3. 原生 HTML + Request.Files | <input type="file" name="file"> |
Request.Files["file"].FileName (瀏覽器差異同方式 2) |
Request.Files["file"].ContentLength > 0 |
Request.Files["file"].SaveAs(path) |
最低,最靈活 |
<!-- Test.aspx -->
<form id="form1" runat="server" enctype="multipart/form-data">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="Red" />
</form>
// Test.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string savePath = Server.MapPath("~/Uploads/") + FileUpload1.FileName;
FileUpload1.SaveAs(savePath);
Label1.Text = "上傳成功!";
}
}
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="file1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="Red" />
</form>
protected void Button1_Click(object sender, EventArgs e)
{
if (file1.PostedFile.ContentLength > 0)
{
string fileName = Path.GetFileName(file1.PostedFile.FileName); // 統一只取檔名
string savePath = Server.MapPath("~/Uploads/") + fileName;
file1.PostedFile.SaveAs(savePath);
Label1.Text = "上傳成功!";
}
}
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" name="file" />
<asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="Red" />
</form>
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile postedFile = Request.Files["file"];
if (postedFile != null && postedFile.ContentLength > 0)
{
string fileName = Path.GetFileName(postedFile.FileName);
string savePath = Server.MapPath("~/Uploads/") + fileName;
postedFile.SaveAs(savePath);
Label1.Text = "上傳成功!";
}
}
UploadObj (副檔名驗證、隨機重命名、文字浮水印)using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
namespace EC
{
public class UploadObj
{
public enum FileType { jpg, gif, bmp, png }
// 取得副檔名
public static string GetFileExtends(string filename)
{
if (string.IsNullOrEmpty(filename)) return null;
int idx = filename.LastIndexOf('.');
return idx > 0 ? filename.Substring(idx + 1).ToLower() : null;
}
// 驗證副檔名是否允許
public static bool CheckFileExtends(string ext)
{
if (string.IsNullOrEmpty(ext)) return false;
foreach (string allowed in Enum.GetNames(typeof(FileType)))
if (allowed.Equals(ext, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
// 儲存檔案 (自動重命名避免衝突)
public static string PhotoSave(string folderPath, FileUpload fu)
{
if (!fu.HasFile) return string.Empty;
string ext = GetFileExtends(fu.FileName);
if (!CheckFileExtends(ext))
throw new Exception("上傳檔案類型不合法");
string newName = $"{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid():N}.{ext}";
string fullPath = Path.Combine(folderPath, newName);
try
{
fu.SaveAs(fullPath);
}
catch (Exception ex)
{
throw new Exception("儲存失敗: " + ex.Message);
}
return newName;
}
// 文字浮水印 (僅示範核心邏輯)
public void AddTextWatermark(string imagePath, string text, string fontFamily = "Arial", int fontSize = 20, Color? color = null, int opacity = 128)
{
if (!File.Exists(imagePath)) throw new FileNotFoundException("圖片不存在", imagePath);
using (Image img = Image.FromFile(imagePath))
using (Graphics g = Graphics.FromImage(img))
using (Font font = new Font(fontFamily, fontSize, FontStyle.Bold))
using (Brush brush = new SolidBrush(Color.FromArgb(opacity, color ?? Color.White)))
{
StringFormat sf = new StringFormat { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far };
g.DrawString(text, font, brush, img.Width - 10, img.Height - 10, sf);
// 覆寫原檔或另存新檔
img.Save(imagePath, img.RawFormat);
}
}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string uploadFolder = Server.MapPath("~/Uploads/");
if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);
try
{
string savedName = UploadObj.PhotoSave(uploadFolder, FileUpload1);
string fullPath = Path.Combine(uploadFolder, savedName);
// 可選:加入浮水印
// new UploadObj().AddTextWatermark(fullPath, "© MySite 2024");
lblMsg.Text = $"上傳成功:{savedName}";
}
catch (Exception ex)
{
lblMsg.Text = "錯誤:" + ex.Message;
}
}
ASP.NET 提供三種層級的檔案上傳 API,`FileUpload` 封裝度最高最適合一般開發;`Request.Files` 靈活度最高適合處理多檔、非標準表單。務必落實副檔名白名單、檔案重命名、儲存目錄隔離、請求大小限制等安全措施。進階需求 (水印、縮圖、轉檔、分塊) 建議引入 ImageSharp、SkiaSharp、FFmpeg 等專業庫處理。