Question

I am attempting to parse the inputstream of an httpListenerRequest and am having serious problems with multipart/form-data.

Heres an example raw post:

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

Now how on earth do i get that image data? I can read the input stream to a string with a stream reader to extract the 1st 5 form variables, but i havent a clue how to extract the image data as converting it to string corrupts it?

Was it helpful?

Solution

check http://msdn.microsoft.com/en-us/library/6196h3wt.aspx to ensure your string is well decoded.

Then convert the part of the string containing the image to byte array with this function:

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

Then convert the byte array to image with this function:

 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top