C#实现⾃定义multipartform-data的解析器
使⽤WebSocketSharp⾃定义实现Web服务时,⽆法解析multipart/form-data请求的数据。通过查资料,采⽤以下⽅式实现multipart/form-data的解析器。
解析辅助类:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace YongFrame.Common.Utils
{
/// <summary>
/// multipart/form-data的解析器
/// </summary>
internal class HttpMultipartParser
{
/// <summary>
/// 参数集合
/// </summary>
public IDictionary<string, string> Parameters = new Dictionary<string, string>();
/// <summary>
/// 上传⽂件部分参数
/// </summary>
public string FilePartName { get; }
/// <summary>
/// 是否解析成功
/// </summary>
public bool Success { get; private set; }
/// <summary>
/// 请求类型
/// </summary>
public string ContentType { get; private set; }
/// <summary>
/// 上传的⽂件名
/
param name// </summary>
public string Filename { get; private set; }
/// <summary>
/// 上传的⽂件内容
/// </summary>
public byte[] FileContents { get; private set; }
/// <summary>
/// 解析multipart/form-data格式的⽂件请求,默认编码为utf8
/// </summary>
/// <param name="stream"></param>
/// <param name="filePartName"></param>
public HttpMultipartParser(Stream stream, string filePartName)
{
FilePartName = filePartName;
Parse(stream, Encoding.UTF8);
}
/// <summary>
/// 解析multipart/form-data格式的字符串
/// </summary>
/// <param name="content"></param>
public HttpMultipartParser(string content)
{
var array = Encoding.UTF8.GetBytes(content);
var stream = new MemoryStream(array);
var stream = new MemoryStream(array);
Parse(stream, Encoding.UTF8);
}
/// <summary>
/// 解析multipart/form-data格式的⽂件请求
/// </summary>
/// <param name="stream"></param>
/// <param name="encoding">编码</param>
/// <param name="filePartName"></param>
public HttpMultipartParser(Stream stream, Encoding encoding, string filePartName)
{
FilePartName = filePartName;
Parse(stream, encoding);
}
private void Parse(Stream stream, Encoding encoding)
{
Success = false;
var data = ToByteArray(stream);
var content = encoding.GetString(data);
var delimiterEndIndex = content.IndexOf("\r\n", StringComparison.Ordinal);
if (delimiterEndIndex > -1)
{
var delimiter = content.Substring(0, content.IndexOf("\r\n", StringComparison.Ordinal)).Trim();
var sections = content.Split(new[] {delimiter}, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in sections)
{
if (s.Contains("Content-Disposition"))
{
var nameMatch = new Regex(@"(?<=name\=\"")(.*?)(?=\"")").Match(s);
var name = nameMatch.Value.Trim().ToLower();
if (name == FilePartName && !string.IsNullOrEmpty(FilePartName))
{
var re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
var contentTypeMatch = re.Match(content);
re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
var filenameMatch = re.Match(content);
if (contentTypeMatch.Success && filenameMatch.Success)
{
ContentType = contentTypeMatch.Value.Trim();
Filename = filenameMatch.Value.Trim();
var startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
var delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
var endIndex = IndexOf(data, delimiterBytes, startIndex);
var contentLength = endIndex - startIndex;
var fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
FileContents = fileData;
}
}
}
else if (!string.IsNullOrWhiteSpace(name))
{
var startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length; Parameters.Add(name, s.Substring(startIndex).TrimEnd('\r', '\n').Trim()); }
}
}
if (FileContents != null || Parameters.Count != 0)
{
Success = true;
}
}
}
public static int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
{
var index = 0;
var startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1)
{
while (startPos + index < searchWithin.Length)
{
if (searchWithin[startPos + index] == serachFor[index])
{
index++;
if (index == serachFor.Length)
{
return startPos;
}
}
else
{
startPos = Array.IndexOf(searchWithin, serachFor[0], startPos + index);
if (startPos == -1)
{
return -1;
}
index = 0;
}
}
}
return -1;
}
public static byte[] ToByteArray(Stream stream)
{
var buffer = new byte[32768];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
return ms.ToArray();
}
ms.Write(buffer, 0, read);
}
}
}
}
}
}
调⽤⽰例:
HttpMultipartParser parser = new HttpMultipartParser(paramData);
if (!parser.Success)
{
result.Code = -1;
result.Message = "请求数据格式不能正确";
return result;
}
if (!parser.Parameters.ContainsKey("optid") || parser.Parameters["optid"] == null || string.IsNullOrEmpty(parser.Parameters["optid"])) {
result.Code = -1;
result.Message = "⽤户名不能为空";
return result;
}
public void Upload(Stream stream)
{
HttpMultipartParser parser = new HttpMultipartParser(stream, "image");
if (parser.Success)
{
string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
string title = HttpUtility.UrlDecode(parser.Parameters["title"]);
// Save the file somewhere
File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论