Server.MapPath("相對路徑") 將虛擬路徑(相對於網站根目錄或當前頁面)轉換為伺服器實體絕對路徑。回傳值以 \ 結尾(目錄)或含檔名。
| 相對路徑 | 對應實體路徑 | 說明 |
|---|---|---|
"test.txt" | C:\Site\CurrentDir\test.txt | 當前頁面目錄下的檔案 |
"sub/test.txt" | C:\Site\CurrentDir\sub\test.txt | 當前目錄下子資料夾 |
"../sibling/test.txt" | C:\Site\ParentDir\sibling\test.txt | 父目錄下的同級資料夾 |
"~/app_data/test.txt" | C:\Site\app_data\test.txt | 波浪號 ~ 代表網站根目錄,最推薦寫法 |
"/test.txt" | C:\Site\test.txt | 根目錄(同 ~) |
// ASP.NET WebForms / MVC Controller 通用
public void UploadFile(HttpPostedFileBase file) // 或 HttpPostedFile
{
if (file == null || file.ContentLength == 0) return;
// 1. 取得純檔名(防止路徑遍歷攻擊)
string fileName = Path.GetFileName(file.FileName);
if (string.IsNullOrWhiteSpace(fileName)) return;
// 2. 產生唯一檔名避免覆蓋
string uniqueName = $"{Guid.NewGuid():N}_{fileName}";
// 3. 目標資料夾:網站根目錄下的 Uploads
string uploadFolder = Server.MapPath("~/Uploads/");
if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);
string fullPath = Path.Combine(uploadFolder, uniqueName);
// 4. 儲存
file.SaveAs(fullPath); // HttpPostedFileBase
// file.SaveAs(fullPath); // HttpPostedFile 同樣方法
}
Path.GetFileName 移除目錄資訊,防止 ../../etc/passwd。.jpg、.pdf、.xlsx 等。file.ContentType,防止偽裝副檔名。web.config 設定 maxRequestLength / maxAllowedContentLength。web.config 禁止執行腳本(<handlers accessPolicy="Read" />)。// IWebHostEnvironment 注入
public class FileService
{
private readonly IWebHostEnvironment _env;
public FileService(IWebHostEnvironment env) => _env = env;
public string SaveUpload(IFormFile file)
{
string uploads = Path.Combine(_env.WebRootPath, "uploads");
Directory.CreateDirectory(uploads);
string fileName = $"{Guid.NewGuid():N}_{Path.GetFileName(file.FileName)}";
string fullPath = Path.Combine(uploads, fileName);
using (var fs = new FileStream(fullPath, FileMode.Create))
file.CopyTo(fs);
return $"/uploads/{fileName}"; // 回傳相對 URL
}
}
| 錯誤 | 原因 | 解決 |
|---|---|---|
路徑包含 .. 導致跳出網站根目錄 | 未驗證使用者輸入路徑 | 永遠用 Path.GetFileName 取純檔名,自行組合路徑 |
| 權限不足:Access denied | IIS_IUSRS / ApplicationPoolIdentity 無寫入權限 | 給上傳資料夾寫入權限,或用 App_Data 目錄(預設有權限) |
| 大檔上傳失敗 (404/413) | 預設限制 4MB / 30MB | 調整 web.config maxRequestLength (KB) / maxAllowedContentLength (Bytes) |
Server.MapPath("~/...") 是 ASP.NET 經典專案處理實體路徑的標準方式,關鍵在於善用波浪號 ~ 代表網站根目錄,避免相對路徑在不同頁面層級下解析不一致。檔案上傳務必落實檔名純化、副檔名白名單、權限隔離、大小限制四大防護。ASP.NET Core 改用 IWebHostEnvironment.WebRootPath / ContentRootPath,邏輯一致、API 更現代。