在 ASP.NET WebForms 中,於 Page_Load 事件處理上傳檔案:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > 0)
{
HttpPostedFile file = Request.Files[0];
string savePath = Server.MapPath("~/Uploads/");
// 確保目錄存在
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
// 組合完整路徑(建議重新命名避免衝突)
string fileName = Path.GetFileName(file.FileName);
string fullPath = Path.Combine(savePath, fileName);
// 儲存檔案
file.SaveAs(fullPath);
// 回應成功訊息(SWFUpload 需要)
Response.Write("SUCCESS");
Response.End();
}
}
Request.Files 集合: SWFUpload 以 multipart/form-data 形式上傳,ASP.NET 自動解析並放入 Request.Files,索引 0 即為第一個檔案。Server.MapPath: 將虛擬路徑 ~/Uploads/ 轉換為實體磁碟路徑。IIS_IUSRS、ApplicationPoolIdentity)需對目標資料夾具備寫入權限。SUCCESS、ERROR:原因),不要輸出 HTML。string safeFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
string fullPath = Path.Combine(savePath, safeFileName);
file.SaveAs(fullPath);
// 記錄對應關係到資料庫
// INSERT INTO UploadFiles (OriginalName, StoredName, UploadTime, UserId) VALUES (...)
[HttpPost]
public async Task Upload(IFormFile file)
{
if (file == null || file.Length == 0) return BadRequest("No file");
var uploads = Path.Combine(_env.WebRootPath, "uploads");
Directory.CreateDirectory(uploads);
var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploads, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
await file.CopyToAsync(stream);
return Ok(new { path = "/uploads/" + fileName });
}
ASP.NET 接收 SWFUpload 核心在 Request.Files[0].SaveAs(),搭配目錄權限、檔案重命名、安全性檢查即可構建穩健的上傳端點。現代專案建議改用 HTML5 <input type="file"> + AJAX/Fetch,淘汰依賴 Flash 的 SWFUpload。