HttpRequest Exception Header section VB.NET - vb.net

I'm trying to upload a file with the following code, but when I upload a file raises an exception: Header section has more than 10240 bytes (maybe it is not properly terminated)
I try with this but isn't work: WebRequest POST with both file and parameters
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
For Each key As String In otherParameters.Keys
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim formItem As String
Dim formItemBytes As Byte()
If key = "file" Then
formItemBytes = StreamFile(otherParameters(key))
Else
formItem = String.Format(formDataTemplate, key, newLine, otherParameters(key))
formItemBytes = Encoding.UTF8.GetBytes(formItem)
End If
requestStream.Write(formItemBytes, 0, formItemBytes.Length)
Next key
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, headerBytes.Length)
Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(4096) As Byte
Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
Do While (bytesRead > 0)
requestStream.Write(buffer, 0, bytesRead)
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
Loop
End Using
Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
End Using
Dim response As Net.WebResponse = request.GetResponse()
EDIT:
I try with two options and not work:
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2} Content-Type: {3}{2}{2}"
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}" & newLine & "Content-Type: {3}{2}{2}"

Related

Uploading File as FormData in vb.net?

I'm having trouble uploading some form data to an API endpoint in vb.net.
Example From Vendor:
curl -X POST -H 'Authorization: Token token=sfg999666t673t7t82'
-H 'Content-Type: multipart/form-data' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
-F file=#/Users/user1/Downloads/download.jpeg -F file_name=nameForFile
-F is_shared=true -F targetable_id=1 -F targetable_type=Lead -X POST "https://domain.freshsales.io/api/documents"
VB.NET CODE
Shameless pulled from (Upload files with HTTPWebrequest (multipart/form-data))
Private Sub HttpUploadFile(ByVal filePath As String, ByVal fileParameterName As String, ByVal contentType As String, ByVal otherParameters As Specialized.NameValueCollection)
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create("https://domain.freshsales.io/api/documents")
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
For Each key As String In otherParameters.Keys
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim formItem As String = String.Format(formDataTemplate, key, newLine, otherParameters(key))
Dim formItemBytes As Byte() = Text.Encoding.UTF8.GetBytes(formItem)
requestStream.Write(formItemBytes, 0, formItemBytes.Length)
Next key
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
Dim headerBytes As Byte() = Text.Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, headerBytes.Length)
Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(4096) As Byte
Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
Do While (bytesRead > 0)
requestStream.Write(buffer, 0, bytesRead)
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
Loop
End Using
Dim trailer As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
End Using
Dim response As Net.WebResponse = Nothing
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
End Using
Catch exception As Net.WebException
response = exception.Response
If (response IsNot Nothing) Then
Using reader As New IO.StreamReader(response.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub
Calling The Function
Here is my call:
Dim headers As NameValueCollection = New NameValueCollection()
headers.Add("Token", "token=youguessedit;")
Dim nvc As NameValueCollection = New NameValueCollection()
nvc.Add("is_shared", true)
nvc.Add("targetable_id", 1)
nvc.Add("targetable_type", "Lead")
HttpUploadFile("c:\test\file.pdf", "file", "application/pdf", nvc, headers);
I think part of my issue is in the way the headers are attached here:
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
In that the API endpoint is expecting file= and file_name= how can I correct the headers?
Can anyone point out where else I have gone wrong? Is there an easier way of doing this?
Here's a simple Console app example using HttpClient with a MultipartFormDataContent which takes care of all the headers and streaming the file, this example also works as-is thanks to Postman-Echo, if there's a requirement for additional headers (only Token is shown here) be sure to add them to the HttpClient.DefaultRequestHeaders
Dim response As New HttpResponseMessage
Dim path As String = "C:\\Temp\\upload.pdf"
Dim uri As New Uri("https://postman-echo.com/post")
Using form As New MultipartFormDataContent,
fs As New FileStream(path, FileMode.Open),
content As New StreamContent(fs),
httpClient As New HttpClient
form.Add(content)
httpClient.DefaultRequestHeaders.Add("Token", "Super Secret")
response = httpClient.PostAsync(uri, form).GetAwaiter.GetResult()
Console.WriteLine("Is Successfull: " & response.IsSuccessStatusCode)
End Using
EDIT: Cleaned up nested Using statements

Docusign API implemention with our web application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want sample codes for send files envelope for signing with specify template, recipients and once signed by all recipients file need to download. I have accessToken, account key with demo sandbox login,Could u provide exact code in vb.net better, if not, then in c#.
2 steps
1.Pass file with recipients (multiple recipients also)
2.Once signed by all recipients get back files instead replay in sender mail
regards,
Aravind
There are plenty of materials for what you are trying to accomplish. You can first start by downloading the c# launcher from https://github.com/docusign/code-examples-csharp. It has 31 examples. You can register for our webinars if you want to ask specific questions here https://www.docusign.com/company/events. You can start as well by reading our guides https://developers.docusign.com/docs/esign-rest-api/how-to/. Another place you can find useful information is https://www.docusign.com/blog/developers.
Here is a basic VB example for DocuSign.
You will need to add OAuth authentication to use it in production.
' DocuSign Builder example. Generated: Wed, 12 Aug 2020 16:35:59 GMT
' DocuSign Ⓒ 2020. MIT License -- https://opensource.org/licenses/MIT
' #see DocuSign Developer Center
Imports System.Net
Imports System.Text
Imports System.IO
Imports Newtonsoft.Json.Linq
Module Program
Const accountId As String = ""
Const accessToken As String = ""
Const baseUri As String = "https://demo.docusign.net"
Const documentDir = "Assets"
Function SendDocuSignEnvelope() As String ' RETURNS envelopeId
' Note: The JSON string constant uses the VB interpolated format.
' See https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/interpolated-strings
' This format enables you to use the JSON as a template within your app, and
' replace values with interpolated/dynamic values. Remember that string values must be
' escaped per the JSON string rules. (Escape " as \")
Dim envelopeDefinition As String = $"{{
""emailSubject"": ""Please sign the attached document"",
""status"": ""sent"",
""documents"": [
{{
""name"": ""Example document"",
""fileExtension"": ""pdf"",
""documentId"": ""1""
}}
],
""recipients"": {{
""signers"": [
{{
""email"": ""signer_email#example.com"",
""name"": ""Signer's name"",
""recipientId"": ""1"",
""clientUserId"": ""1000"",
""tabs"": {{
""signHereTabs"": [
{{
""anchorString"": ""/sig1/"",
""anchorXOffset"": ""20"",
""anchorUnits"": ""pixels""
}}
]
}}
}}
]
}}
}}"
Dim documents = {
(mimeType:="application/pdf", filename:="Example document", documentId:="1", diskFilename:="anchorfields.pdf")
}
Dim url As String = $"{baseUri}/restapi/v2.1/accounts/{accountId}/envelopes"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
Dim CRLF As String = vbCrLf
Dim boundary As String = "multipartboundary_multipartboundary"
Dim hyphens As String = "--"
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.ContentType = $"multipart/form-data; boundary={boundary}"
postReq.Accept = "application/json"
postReq.Headers.Add("Authorization", $"Bearer {accessToken}")
postReq.UserAgent = "DS Builder tool VB"
' Send request as a multipart mime message with the
' documents included in binary format (not Base64 encoded)
Dim encoding As New UTF8Encoding
Dim byteData As Byte()
Dim stringBuffer As String
Dim postreqstream As Stream = postReq.GetRequestStream()
Dim postLength As Int32 = 0
Dim rawFilePath As String = Directory.GetCurrentDirectory() ' \\Mac\Home\www\VB_Example\VB_Example\bin\Debug\netcoreapp3.1\
Dim docFilePath As String = Path.GetFullPath(Path.Combine(rawFilePath, "..\..\..\" & documentDir & "\"))
Dim document As (mimeType As String, filename As String, documentId As String, diskFilename As String)
stringBuffer = 'Send preamble and JSON request
hyphens & boundary & CRLF & "Content-Type: application/json" &
CRLF & "Content-Disposition: form-data" & CRLF & CRLF & envelopeDefinition
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
For Each document In documents
stringBuffer = CRLF & hyphens & boundary & CRLF & $"Content-Type: {document.mimeType}" &
CRLF & $"Content-Disposition: file; filename=""{document.filename}"";documentid={document.documentId}" & CRLF & CRLF
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
' add the file's contents
Dim inputFile = File.Open(docFilePath & document.diskFilename, FileMode.Open)
' 1/2 Megabyte buffer. Dim statements specifies last index, so we subtract 1
Dim bufferSize As Integer = 1024 * 512
Dim bytes = New Byte(bufferSize - 1) {}
Dim bytesRead As Int32 = inputFile.Read(bytes, 0, bufferSize)
While bytesRead > 0
postreqstream.Write(bytes, 0, bytesRead)
postLength += bytesRead
bytesRead = inputFile.Read(bytes, 0, bufferSize)
End While
inputFile.Close()
Next
stringBuffer = CRLF & hyphens & boundary & hyphens & CRLF 'Send postamble
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
postReq.ContentLength = postLength
Try
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader = New StreamReader(postresponse.GetResponseStream())
Dim resultsJSON As String = postreqreader.ReadToEnd
Console.WriteLine($"Create envelope results: {resultsJSON}")
Dim resultsJObj As JObject = JObject.Parse(resultsJSON)
Dim envelopeId As String = resultsJObj("envelopeId")
Console.WriteLine($"EnvelopeId: {envelopeId}")
Return envelopeId
Catch Ex As WebException
Console.WriteLine($"Error while creating envelope! {Ex.Message}")
If Ex.Response IsNot Nothing Then
Console.WriteLine($"Error response: {New StreamReader(Ex.Response.GetResponseStream).ReadToEnd}")
End If
Return ""
End Try
End Function
Sub RecipientView(envelopeId As String)
Dim doRecipientView As Boolean = True
Dim recipientViewRequest As String = $"{{
""returnUrl"": ""https://docusign.com"",
""authenticationMethod"": ""none"",
""clientUserId"": ""1000"",
""email"": ""signer_email#example.com"",
""userName"": ""Signer's name""
}}"
Dim url As String = $"{baseUri}/restapi/v2.1/accounts/{accountId}/envelopes/{envelopeId}/views/recipient"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.ContentType = "application/json"
postReq.Accept = "application/json"
postReq.Headers.Add("Authorization", $"Bearer {accessToken}")
postReq.UserAgent = "DS Builder tool VB"
Dim encoding As New UTF8Encoding
Dim byteData As Byte()
Dim postreqstream As Stream = postReq.GetRequestStream()
byteData = encoding.GetBytes(recipientViewRequest)
postreqstream.Write(byteData, 0, byteData.Length)
postReq.ContentLength = byteData.Length
Try
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader = New StreamReader(postresponse.GetResponseStream())
Dim resultsJSON As String = postreqreader.ReadToEnd
Dim resultsJObj As JObject = JObject.Parse(resultsJSON)
Dim viewUrl As String = resultsJObj("url")
Console.WriteLine("Create recipient view succeeded.")
Console.WriteLine("Open the signing ceremony's long URL within 5 minutes:")
Console.WriteLine(viewUrl)
Catch Ex As WebException
Console.WriteLine($"Error requesting recipient view! {Ex.Message}")
If Ex.Response IsNot Nothing Then
Console.WriteLine($"Error response: {New StreamReader(Ex.Response.GetResponseStream).ReadToEnd}")
End If
End Try
End Sub
' The mainline
Sub Main(args As String())
Console.WriteLine("Starting...")
Dim envelopeId As String = SendDocuSignEnvelope()
RecipientView(envelopeId)
Console.WriteLine("Done.")
End Sub
End Module

Twitter upload/media Append

I just can't wrap my mind around how to do the append step. I've already done the INIT part without trouble but I don't understand how to do the next step.
What I'm doing now : I build a authorization header with only the oauth parameters and the signature base too, then I put the required parameters into the body request : command=APPEND, media_id from the INIT method, media with the raw binary image, and segment_index=0 because I have to send only one request since the size of my image is never more than 30 kB.
I have tried the following:
Dim oHttpWebRequest As HttpWebRequest
Dim oHttpWebResponse As HttpWebResponse
Dim oStream As Stream
Dim newLine As String = System.Environment.NewLine
Dim mediaId = getINITresponse()
Try
oHttpWebRequest = DirectCast(WebRequest.Create("https://upload.twitter.com/1.1/media/upload.json"), HttpWebRequest)
Dim sBody As String = buildHeader(twitter, sAuth)
oHttpWebRequest.Headers.Add("Authorization", sBody)
oHttpWebRequest.Method = "POST"
Dim sBoundary As String = DateTime.Now.Ticks.ToString("x")
Dim sStartBoundary As String = "--" + sBoundary + newLine
Dim sEndBoundary As String = newLine + "--" + sBoundary + "--" + newLine
oHttpWebRequest.ContentType = "multipart/form-data; boundary=" + sBoundary
Dim sBodyData As String = ""
Dim srequestString As New StringBuilder()
sBodyData = "command=APPEND&media_id=" + mediaId + "&segment_index=0&media="
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""media""; filename=""image.jpg""" + newLine)
srequestString.AppendLine(Encoding.Default.GetString(getBinaryFileFromPath(sFicName)))
srequestString.AppendLine(newLine + sEndBoundary + newLine)
Dim postData As Byte()
postData = Text.Encoding.UTF8.GetBytes(sBodyData)
Dim postDataBytes As Byte()
postDataBytes = Text.Encoding.UTF8.GetBytes(srequestString.ToString())
Dim byteResult() As Byte = postData.Concat(postDataBytes).ToArray()
oHttpWebRequest.ContentLength = byteResult.Length
Using requestStream = oHttpWebRequest.GetRequestStream()
requestStream.Write(byteResult, 0, byteResult.Length)
requestStream.Close()
End Using
oHttpWebResponse = DirectCast(oHttpWebRequest.GetResponse(), HttpWebResponse)
oStream = oHttpWebResponse.GetResponseStream()
Return New StreamReader(oStream, Encoding.UTF8).ReadToEnd()
Catch wex As WebException 'Exception venant du serveur distant
Return New StreamReader(wex.Response.GetResponseStream()).ReadToEnd()
End Try
My Init part is working and I save the media_id and use it for the Append part. My image is no more than 30 kB so it's not a problem of size.
Twitter respond me with the status : 400 Bad Request.
I don't know what I am doing wrong. Sorry for my bad english!
I find the answer:
sBodyData = "command=APPEND&media_id=" + mediaId + "&segment_index=0&media="
I was making my body data as if I was sending a request with ContentType=application/x-www-form-urlencoded.
So I used both of the contentType in the same request and of course it wasn't working. Now it looks like that:
Dim newLine As String = System.Environment.NewLine
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""command""" + newLine)
srequestString.AppendLine("APPEND")
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""media_id""" + newLine)
srequestString.AppendLine(mediaId)
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""media""" + newLine)
srequestString.AppendLine(Encoding.Default.GetString(getBinaryFileFromPath(sFileName)))
srequestString.AppendLine(sStartBoundary + "Content-Disposition: form-data; name=""segment_index""" + newLine)
srequestString.AppendLine("0")
srequestString.AppendLine(sEndBoundary)

Prestashop - Unable to upload a new image product with the prestashop 1.6 webservice

I'm trying to upload a new image for a product with the prestashop webservice through a vb .net application, but I get the following error message:
"Unable to save this image".
The URL used to upload the image is this: http://localhost/prestashop/api/images/products/1
And the source code of the function that make the request is this:
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Image)
Dim response As String = Nothing
Try
Dim ms As New MemoryStream()
imageToAdd.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim byteArray As Byte() = ms.ToArray()
Dim requestUrl As String = Me.WebServiceURL & "/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.Method = WebServicePrestashop.CRUDMethod.Create
'webRequest.ContentType = "image/jpeg"
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = byteArray.Length
MsgBox(byteArray.Length)
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)
Dim imageNew As Image = Image.FromStream(webResponse.GetResponseStream())
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub
I'm using the HTTP POST method, and the POST content is the bynary content of the new image.
How can I fix it?.
Here the solution.
I think the key is that I must write the body of the webrequest programatically adding to the stream of the webrequest the boundary (in binary array format), the Content-Type chain (in binary array format) and the content of the image to upload (in binary array format).
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Byte())
Dim response As String = Nothing
Try
Dim requestUrl As String = "urlShop" & "/api/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.KeepAlive = True
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = imageToAdd.Length
webRequest.Method = "POST"
webRequest.ContentType = "image/jpeg"
Dim boundary As String = "----" & DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture)
webRequest.ContentType = "multipart/form-data; boundary=" & boundary
Dim beginPostData = "--" & boundary & vbCrLf & "Content-Disposition: form-data; name=""image""; filename=""torrente.jpg""" & _
vbCrLf & "Content-Type: image/jpeg" & vbCrLf & vbCrLf
Dim boundaryBytes = System.Text.Encoding.ASCII.GetBytes(vbCrLf & "--" & boundary & "--" & vbCrLf)
Dim beginPostDataBytes = System.Text.Encoding.ASCII.GetBytes(beginPostData)
webRequest.ContentLength = beginPostData.Length + imageToAdd.Length + boundaryBytes.Length
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(beginPostDataBytes, 0, beginPostDataBytes.Length)
dataStream.Write(imageToAdd, 0, imageToAdd.Length)
dataStream.Write(boundaryBytes, 0, boundaryBytes.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream())
response = reader.ReadToEnd()
MsgBox(response)
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub

VB.NET - How To Get Raw Image Data To String

How would I get raw image data to a String in VB.NET similar to the following:
J©õݨe‚Lnž¿Ëã/ǧúÐ5ý¼C÷Cý>ß’t;fm—=Äw:�/E±ËÙÏ$á#%Pc>× Šgw.²Ab“:ÅÓù:ϯÌh6à€Z§Ó‚g£®hÚD6¨Ø^Ú2ô`ä¨L�YÆÄÅCX#I“ÈÌãj¦L˜•’|¥�Eb¡ëQ–¤Ú, 3\UzL öÔoj4�•±’u«c¼#„oÕ`îF>·o—ŠûÅ«ÎÑ™¶Ç˜ýº*i°œÈVŒ�Qû”Ñ[.�ÔmçE•ì¦eNCh�Ù
é§�É$m¿ôš"»ÌNæ(VÌmp›F¹XÈ88™ªüµ…d•XµÔÜ#�ˆŠv‘º‚F‚§Yûb
My current code is:
Dim FileName As String = "Image.jpg"
Dim ImageData() As Byte = File.ReadAllBytes(ProfileImagePath)
Dim NewImageData As String = Convert.ToBase64String(ImageData)
This returns the Base64 code but I am trying to get the actual raw data like in the example above so that I can POST to a multipart upload form which also posts in this way.
My full code for the upload being:
Dim boundary As String = "-----------------------------" & DateTime.Now.Ticks.ToString("x")
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.mysite.com/upload.php"), HttpWebRequest)
req.Method = "POST"
req.ContentType = "multipart/form-data; boundary=" & "---------------------------" & DateTime.Now.Ticks.ToString("x")
req.KeepAlive = False
Dim builder As New StringBuilder()
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""variable1""" & vbCrLf & vbCrLf & "1" & vbCrLf)
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""file""; filename=""" & FileName & """" & vbCrLf)
builder.Append("Content-Type: application/octet-stream")
builder.Append(vbCrLf & vbCrLf)
' Add Photo Here
If UpdateImage = True Then
' Load Image
Dim ImageData() As Byte = File.ReadAllBytes(ProfileImagePath)
Dim NewImageData As String = Convert.ToBase64String(ImageData)
' Add Image To Header
builder.Append(NewImageData)
builder.Append(vbCrLf)
Else
builder.Append(vbCrLf)
End If
builder.Append(boundary & vbCrLf & "Content-Disposition: form-data; name=""save""" & vbCrLf & vbCrLf & "save")
' Footer Bytes
Dim close As Byte() = Encoding.UTF8.GetBytes("--")
Dim postHeader As String = builder.ToString()
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCrLf & boundary & "--" & vbCrLf)
Dim length As Long = postHeaderBytes.Length + boundaryBytes.Length
req.ContentLength = length
Dim requestStream As Stream = req.GetRequestStream()
Dim fulllength As Integer = postHeaderBytes.Length + boundaryBytes.Length
' Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
' Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim responce As WebResponse
responce = req.GetResponse()
requestStream.Close()
Dim s As Stream = responce.GetResponseStream()
Dim sr As New StreamReader(s)
Dim Content As String = sr.ReadToEnd()
This returns the Base64 code but I am trying to get the actual raw data like in the example above
The "actual raw data" isn't text data so you shouldn't put it in a string at all; at least not without something like base64.
If you want to post binary data, then either use base64 or post it as raw bytes, but not as text. Your data is not UTF-8-encoded text, so don't try to use it as if it were.
(I can't remember the details of multi-part form data; if you can specify a part length before the part itself, then you should be fine to include the binary data directly. If it's always just delimited by some separator, then you may want to use base64 instead.)