我根据RFC1867和HttpWorkerRequest取得了上传表单的内容,然后将其内容转为字符串,通过协议的规范来提取上传文件的数据
但是保存时出现编码问题,如果是txt文件保存不会有问题,当如果上传的是图片或word文档,保存到硬盘后还是不能正常打开。用UE打开和原文件对比二进制数据之间有差异。我试过UTF-8,ASCII,unicode编码都不行。先利用 request.GetPreloadedEntityBody() 和 request.ReadEntityBody()读取表单数据,然后每两个数据块解析一次。
解析文件数据后就可以实时保存到硬盘,而不需要等到文件全部加载完再保存。  WebForm内容格式如下:
-----------------------------7d33a816d302b6
Content-Disposition: form-data; name="userfile1"; filename="E:\abc.txt"\r\n
Content-Type: application/octet-stream\r\n
    \r\n
内容
-----------------------------7d33a816d302b6
所以只需找到分隔符(分隔符可以在request.ContentType找到,不过少两个-)和filename的位置即可确定文件内容的范围。具体代码为: /// <summary>
/// 根据RFC1867协议解析
/// 累计两个数据块就比较一次
/// </summary>
private void ResolveProtocol(Byte[] bytes)
{
if(m_gbuffer == null)
{
m_gbuffer = bytes;
}
else
{
    byte[] combineByte = new byte[m_gbuffer.Length + bytes.Length]; Buffer.BlockCopy(m_gbuffer,0,combineByte,0,m_gbuffer.Length);
Buffer.BlockCopy(bytes,0,combineByte,m_gbuffer.Length,bytes.Length); string sContent = System.Text.Encoding.GetEncoding("GB2312").GetString(combineByte);  //转为字符串 int boundary_pos = sContent.IndexOf(m_boundary); if(boundary_pos != -1) //是否有分隔符
{
sContent = sContent.Substring(boundary_pos + m_boundary.Length,
  sContent.Length - boundary_pos - m_boundary.Length); string filename = "filename=";
int file_pos = sContent.IndexOf(filename); if(file_pos != -1) //是否有文件数据
{
sContent = sContent.Substring(file_pos + filename.Length,sContent.Length - file_pos - filename.Length); string Db_CRLF = "\r\n\r\n";
string CRLF = "\r\n"; int crlf_pos = sContent.IndexOf(Db_CRLF);

if(crlf_pos != -1) //是否有两个连着的换行符
{
sContent = sContent.Substring(crlf_pos + Db_CRLF.Length,sContent.Length - crlf_pos - Db_CRLF.Length); boundary_pos = sContent.IndexOf(CRLF + m_boundary);

if(boundary_pos != -1) //找到下一个分隔符,获得全部文件数据
{
sContent = sContent.Substring(0,boundary_pos);
} //保存已上传的数据
System.IO.FileStream fs = new FileStream(@"D:\\upload.txt",System.IO.FileMode.Append,System.IO.FileAccess.Write);

byte[] fileData = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sContent);

fs.Write(fileData,0,fileData.Length);

fs.Close();
}
}
} m_gbuffer = new byte[bytes.Length];
Buffer.BlockCopy(bytes,0,m_gbuffer,0,bytes.Length);
}
}