如何从httpListenerRequest解析文件数据

时间:2012-09-06 15:25:50

标签: .net vb.net bytearray httplistener

我正在尝试解析httpListenerRequest的输入流,并且遇到了multipart / form-data的严重问题。

这是一个原始帖子的例子:

POST http://removed/ HTTP/1.1
Content-Type: multipart/form-data; boundary=-------------------------8cf5a569f9a4d4a
Host: removed
Content-Length: 15600
Expect: 100-continue
Proxy-Connection: Keep-Alive



---------------------------8cf5a569f9a4d4a
Content-Disposition: form-data; name="realname"

james
---------------------------8cf5a569f9a4d4a
Content-Disposition: form-data; name="username"

jrb1978
---------------------------8cf5a569f9a4d4a
Content-Disposition: form-data; name="password"

password
---------------------------8cf5a569f9a4d4a
Content-Disposition: form-data; name="public"

0
---------------------------8cf5a569f9a4d4a
Content-Disposition: form-data; name="group"

0
---------------------------8cf5a569f9a4d4a
Content-Disposition: form-data; name="avatar"; filename="Untitled.png"
Content-Type: image/png

?PNG
//jibberish filedata here
---------------------------8cf5a569f9a4d4a

现在我如何获得图像数据? 我可以使用流读取器将输入流读取到字符串中以提取前5个表单变量,但我不知道如何将图像数据转换为字符串会破坏图像数据吗?

1 个答案:

答案 0 :(得分:1)

检查http://msdn.microsoft.com/en-us/library/6196h3wt.aspx以确保您的字符串解码良好。

然后使用此函数将包含图像的字符串部分转换为字节数组:

 Public Shared Function StrToByteArray(str As String) As Byte()
    Dim encoding As New System.Text.UTF8Encoding()
    Return encoding.GetBytes(str)
 End Function 'StrToByteArray

然后使用此函数将字节数组转换为图像:

 Private Function BytesToImage(ByVal ImageBytes() As Byte) As Image
    Dim imgNew As Image
    Dim memImage As New System.IO.MemoryStream(ImageBytes)
    imgNew = Image.FromStream(memImage)
    Return imgNew
 End Function