首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 網絡硬盤實作 (三):檔案上傳 (含大檔案分塊上傳)

     編輯:關於ASP.NET

基本上傳:FileUpload 控制項 (小檔案 < 10MB)





protected void btnUpload_Click(object sender, EventArgs e)
{
 if (!fuFile.HasFile) { lblMsg.Text = "請選擇檔案"; return; }

 FileInfo fi = new FileInfo(fuFile.FileName);
 string destPath = Path.Combine(CurrentPath, fi.Name);

 // 同名檔案處理:覆蓋/重命名/版本
 if (File.Exists(destPath)) { /* 處理邏輯 */ }

 try
 {
 fuFile.SaveAs(destPath); // 內部使用 PostedFile.SaveAs
 LoadDirectory(CurrentPath);
 lblMsg.Text = "上傳成功";
 }
 catch (Exception ex)
 {
 lblMsg.Text = "上傳失敗: " + ex.Message;
 }
}

web.config 上傳大小限制


 
  


 
 
 
  
 
 

兩者必須同時設定,取較小值為實際限制。

大檔案分塊上傳:前端切片 + 後端合併

前端 (JavaScript / Plupload / Dropzone / 自行實作)


// 核心邏輯:File.slice(start, end) → FormData append → POST /UploadChunk.ashx
// 參數: fileId (GUID), chunkIndex, totalChunks, fileName, totalSize
// 伺服器回傳: { success: true, receivedChunks: [0,1,2] }
// 所有分塊完成 → POST /MergeChunks.ashx?fileId=...&fileName=...&targetPath=...

後端:Chunk Handler

public class UploadChunkHandler : IHttpHandler
{
 public void ProcessRequest(HttpContext context)
 {
 string fileId = context.Request.QueryString["fileId"];
 int chunkIndex = int.Parse(context.Request.QueryString["chunkIndex"]);
 string tempDir = Path.Combine(Server.MapPath("~/App_Data/UploadTemp"), fileId);
 Directory.CreateDirectory(tempDir);

 string chunkPath = Path.Combine(tempDir, chunkIndex.ToString("D5"));
 using (FileStream fs = new FileStream(chunkPath, FileMode.Create, FileAccess.Write))
 {
 context.Request.InputStream.CopyTo(fs);
 }

 // 回傳已收到分塊清單
 var received = Directory.GetFiles(tempDir).Select(f => int.Parse(Path.GetFileNameWithoutExtension(f))).OrderBy(x => x).ToList();
 context.Response.ContentType = "application/json";
 context.Response.Write($"{{\"success\":true,\"receivedChunks\":[{string.Join(",", received)}]}}");
 }

 public bool IsReusable => false;
}

後端:Merge Handler

public class MergeChunksHandler : IHttpHandler
{
 public void ProcessRequest(HttpContext context)
 {
 string fileId = context.Request.QueryString["fileId"];
 string fileName = context.Request.QueryString["fileName"];
 string targetPath = context.Request.QueryString["targetPath"]; // 伺服器端絕對路徑

 string tempDir = Path.Combine(Server.MapPath("~/App_Data/UploadTemp"), fileId);
 string[] chunks = Directory.GetFiles(tempDir).OrderBy(f => f).ToArray();

 using (FileStream output = new FileStream(targetPath, FileMode.Create, FileAccess.Write))
 {
 foreach (string chunk in chunks)
 {
 using (FileStream fs = new FileStream(chunk, FileMode.Open, FileAccess.Read))
 fs.CopyTo(output);
 }
 }

 // 清理暫存
 Directory.Delete(tempDir, true);

 context.Response.ContentType = "application/json";
 context.Response.Write("{\"success\":true,\"message\":\"合併完成\"}");
 }

 public bool IsReusable => false;
}

進階功能

  • 斷點續傳:頁面載入時檢查 `UploadTemp/{fileId}` 已存在分塊,前端跳過已上傳分塊。
  • 秒傳:上傳前計算檔案 SHA-256 (Web Worker 避免阻塞 UI),送至伺服器比對資料庫,存在則直接建立連結/記錄。
  • 進度條:`XMLHttpRequest.upload.onprogress` 事件更新 UI。
  • 多檔案佇列:Dropzone.js / Fine Uploader / Uppy 整合。

安全性檢查清單

  • 檔案類型驗證:Magic Number (檔頭) + 副檔名雙重檢查。
  • 病毒掃描:整合 ClamAV / Windows Defender / 雲端掃描 API。
  • 儲存路徑隨機化:`Guid.NewGuid()` + 原始副檔名,避免路徑猜測、覆蓋系統檔案。
  • 權限控管:上傳目錄設定 `Execute` 權限移除,防止上傳 `.aspx`/`.ashx` 執行代碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved