// 手動尋找最後一個 \ 截取文件名,跨平台不可靠
int a = filePath.LastIndexOf("\\");
string fileName = filePath.Substring(a + 1);
缺陷:Windows 用 `\`,Linux/Mac 用 `/`,手動解析不具可移植性。
using System.IO;
string fileName = Path.GetFileName(fileUpload.PostedFile.FileName); // 僅文件名
string ext = Path.GetExtension(fileName); // 副檔名
string dir = Path.GetDirectoryName(filePath); // 目錄部分
if (fileUpload.HasFile) {
string fileName = Path.GetFileName(fileUpload.FileName);
// 1. 目標物理路徑 = 虛擬路徑映射 + 文件名
string virtualPath = "~/Uploads/"; // 虛擬目錄
string physicalPath = Server.MapPath(virtualPath); // 物理路徑
if (!Directory.Exists(physicalPath)) Directory.CreateDirectory(physicalPath);
string fullPath = Path.Combine(physicalPath, fileName);
// 2. 保存
fileUpload.SaveAs(fullPath);
// 3. 數據庫存虛擬路徑供前端訪問
string dbPath = VirtualPathUtility.Combine(virtualPath, fileName);
}
| 術語 | 含義 | 示例 |
|---|---|---|
| 虛擬路徑 | 相對 Web 應用根目錄的路徑 | ~/Uploads/abc.jpg |
| 物理路徑 | 服務器磁盤絕對路徑 | C:\inetpub\wwwroot\Uploads\abc.jpg |
| Server.MapPath | 虛擬 → 物理 | Server.MapPath("~/Uploads") |
| VirtualPathUtility.Combine | 虛擬路徑安全拼接 | Combine("~/Uploads/", "a.jpg") |