在 ASP.NET 中處理檔案上傳時,開發者常會困惑於如何取得用戶端選取檔案的完整路徑。由於瀏覽器安全性限制,前端 `` 僅提供檔案名稱,無法直接取得本機完整路徑。本文將說明正確的處理方式:透過 `HttpFileCollection` 取得上傳檔案流,並儲存至伺服器或資料庫。
HttpFileCollection files = HttpContext.Current.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile postedFile = files[i];
// 後續處理...
}
string fileName = Path.GetFileName(postedFile.FileName); // 僅取得檔名+副檔名
int dotIndex = fileName.LastIndexOf('.');
string fileExtension = (dotIndex > 0) ? fileName.Substring(dotIndex).ToLower() : "";
Guid fileGuid = Guid.NewGuid();
string newFileName = fileGuid.ToString() + fileExtension;
if (postedFile.ContentLength > 2097151 * 1024) // 2GB
{
// 顯示錯誤訊息並返回
return;
}
string serverPath = Server.MapPath("~/Upload/") + newFileName;
postedFile.SaveAs(serverPath);
NRModel.File model = new NRModel.File();
model.Fileid = Guid.NewGuid();
model.Folderid = new Guid(FolderId);
model.Filepath = serverPath;
model.FileNam = fileName;
model.FileSize = postedFile.ContentLength;
model.Decription = TextArea1.Value;
model.CreateOn = DateTime.Now;
// 呼叫 BLL 新增
NRBLL.File bll = new NRBLL.File();
if (bll.FN_AddNewRes(model) > 0)
{
// 記錄日誌、提示成功
}
public void FN_UpFiles()
{
HttpFileCollection files = HttpContext.Current.Request.Files;
try
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile postedFile = files[i];
string fileName = Path.GetFileName(postedFile.FileName);
int dotIndex = fileName.LastIndexOf('.');
string fileExtension = (dotIndex > 0) ? fileName.Substring(dotIndex).ToLower() : "";
Guid fileGuid = Guid.NewGuid();
string newFileName = fileGuid.ToString() + fileExtension;
// 檔案大小檢查
if (postedFile.ContentLength > 2097151 * 1024)
{
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('上傳檔案過大!');", true);
return;
}
if (!string.IsNullOrEmpty(fileName))
{
try
{
string savePath = Server.MapPath("~/Upload/") + newFileName;
// 資料庫記錄
NRModel.File model = new NRModel.File
{
Fileid = Guid.NewGuid(),
Folderid = new Guid(FolderId),
Filepath = savePath,
FileNam = fileName,
FileSize = postedFile.ContentLength,
Decription = TextArea1.Value,
CreateOn = DateTime.Now,
CreateBy = Guid.NewGuid(),
ModefyBy = Guid.NewGuid()
};
NRBLL.File bll = new NRBLL.File();
if (bll.FN_AddNewRes(model) > 0)
{
postedFile.SaveAs(savePath);
NR.Error.Log.LogType($"上傳資源 {fileName} 成功!伺服器路徑:{savePath}");
ScriptManager.RegisterStartupScript(this, GetType(), "success", "alert('上傳成功!');", true);
}
}
catch (Exception ex)
{
NR.Error.Log.LogType(ex.ToString());
}
}
else
{
Response.Write("上傳檔案不能為空!");
NR.Error.Log.LogType("檔案不能為空!");
}
}
}
catch (Exception ex)
{
NR.Error.Log.LogType(ex.ToString());
}
}
若需提升使用者體驗,可搭配 jQuery Form Plugin、Fine Uploader 或 ASP.NET Core 的 `IFormFile` 實作非同步分塊上傳、進度顯示、拖曳上傳等功能。傳統 Web Forms 亦可透過 `AsyncFileUpload` 控制項或自訂 HttpHandler 達成。
總結:ASP.NET 取得上傳檔案的正確做法是透過 `Request.Files` 取得 `HttpPostedFile` 物件,僅能取得檔名與副檔名,不可取得客戶端完整路徑。儲存時建議使用 GUID 重新命名,並同步寫入資料庫紀錄,做好大小、型別驗證與錯誤處理,即可構建安全可靠的上傳功能。