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

ASP.NET 從 Request 輸入流解析參數與檔案 (非標準 multipart 處理)

     編輯:ASP.NET 基礎

應用場景

合作廠商模擬 POST 格式不標準,導致 Request.Form、Request.Files 皆無法取值,需自行解析 Request.InputStream。

解析思路

  1. 讀取完整二進位輸入流 Request.BinaryRead(Request.TotalBytes)。
  2. 以 UTF-8 解碼為字串 (僅分析非檔案部分,避免二進位干擾)。
  3. 使用 RegEx 比對欄位標頭與結尾 boundary,計算其位元組長度 headLength、footLength。
  4. 檔案區段位置 = headLength,長度 = total - headLength - footLength。
  5. 以 MemoryStream 或陣列複製取出檔案內容或存檔。

核心程式碼

byte[] input = Request.BinaryRead(Request.TotalBytes);
string source = Encoding.UTF8.GetString(input);

// 1. 正則比對非檔案部分 (Header + 所有欄位 + 分隔線)
Regex rg = new Regex(@"你的HeaderPattern", RegexOptions.Singleline);
if (!rg.IsMatch(source)) return;

int headLength = Encoding.UTF8.GetBytes(rg.Match(source).Value).Length;

// 2. 結尾 boundary 固定長度 (含 \r\n)
string tail = "\r\n--" + boundary + "--\r\n";
int footLength = Encoding.UTF8.GetBytes(tail).Length;

// 3. 存檔
using (var fss = new FileStream(savePath, FileMode.Create))
{
    fss.Write(input, headLength, input.Length - headLength - footLength);
}

// 4. 或取得檔案位元組陣列
byte[] fileBytes = new byte[input.Length - headLength - footLength];
using (var ms = new MemoryStream(input))
{
    ms.Seek(headLength, SeekOrigin.Begin);
    ms.Read(fileBytes, 0, fileBytes.Length);
}

風險提醒

  • 需精確計算 headLength/footLength,任何多漏 \r\n 皆會導致檔案損毀。
  • 多檔案上傳時 boundary 結構較複雜,建議改用成熟元件 (如 HttpPostedFile、MultipartFormDataParser)。
  • 編碼必須與客戶端一致,建議雙方約定 UTF-8。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved