2

我正在尝试解析 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 个表单变量,但我不知道如何提取图像数据,因为将其转换为字符串会损坏它?

4

1 回答 1

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
于 2012-12-16T21:36:42.963 回答