首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET 接收 SWFUpload 上傳檔案的伺服器端實作

     編輯:程式設計綜合問答

快速實作範例

在 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 執行身分(如 IIS_IUSRS、ApplicationPoolIdentity)需對目標資料夾具備寫入權限。
  • 回應格式: SWFUpload 預期純文字回應(如 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 (...)
  • 使用 GUID 重命名避免同名覆寫與特殊字元問題。
  • 驗證副檔名、MIME 類型、檔案大小,防止惡意上傳。
  • 將上傳目錄設為非執行權限(IIS Handler Mappings 移除 *.aspx, *.ashx 等),防止上傳腳本執行。

ASP.NET Core / MVC 版本

[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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved