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.)
Related
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)
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
I am trying to upload a multi-part form with HTTPWebRequest & all is ok until I added an image to upload, mainly I am trying to do exactly the same request as a browser makes which looks like this:
-----------------------------41184676334
Content-Disposition: form-data; name="file"; filename="guitar tape.jpg"
Content-Type: image/jpeg
IMAGEDATAHERE
-----------------------------41184676334
Content-Disposition: form-data; name="save"
save
-----------------------------41184676334--
I am lost on how to format / read the image to set it into the request that I am making below:
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 System.Drawing.Image
Dim fs As New System.IO.FileStream(ImagePath, System.IO.FileMode.Open)
ImageData = Image.FromStream(fs)
fs.Close()
' Add Image To Header
builder.Append(ImageData)
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()
At the moment it is simply posting "System.Drawing.Bitmap" as the image data but I am not sure how to get the same raw data for the image that looks like this:
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
Any ideas on how I could do this or would I need to change my methods?
builder.Append(ImageData)
is not correct. you need read the image as byte, then add the byte[] to the multipart post.
see details at Using HttpWebRequest to POST data/upload image using multipart/form-data
and make sure use a http sniffer (i.e. fiddler) to see what it is actually sending.
first, load image into byte array, then convert it to base64:
imgBase64 = Convert.ToBase64String(my_image_byte_array)
My "OpenFileDialog" name is "file". When a "button" is clicked it will show a pop up dialog for selecting jpg, jpeg, png image files, it can also add bmp or any image file type. Then after the selection of a image file it will show on "PictureBox" i name it as "picboxProfileID".
In Visual Basic:
file.Filter = "image file (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png | all files (*.*) | *.*"
If (file.ShowDialog <> Windows.Forms.DialogResult.Cancel) Then
picboxProfileID.Image = Image.FromFile(file.FileName)
picboxProfileID.ImageLocation = file.FileName
txtName.Text = file.FileName
My.Computer.Network.UploadFile(file.FileName, "http://localhost/VTVTS/uploadImageSample.php")
Else
picboxProfileID.Image = Nothing
End If
The destination of the file uploaded will be uploaded on the "images/" of the parent folder php file created.
In PHP:
<?php
$response = array();
$image = $_FILES['file'];
$imageName = $image['name'];
$imageTmpName = $image['tmp_name'];
$imageSize = $image['size'];
$imageError = $image['error'];
$imageType = $image['type'];
$fileExt = explode('.', $imageName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'images/'.$fileNameNew;
$newDestination = move_uploaded_file($imageTmpName, $fileDestination);
$response['error'] = false;
$response['message'] = "Upload Image Successful";
}else{
$response['error'] = true;
$response['message'] = "You cannot upload files of this type!";
}
echo json_encode($response);
Happy Coding!
I am trying to make a voice recognition thing with google's voice api.
I modified UPLOADFILEEX function that can be found on codeproject...
The file I wish to delete is C:\record.flac
Here is the function below
Public Shared Function UploadFile(ByVal uploadfilename As String, ByVal url As String, ByVal fileFormName As String, ByVal contenttype As String, ByVal querystring As System.Collections.Specialized.NameValueCollection, ByVal cookies As CookieContainer) As String
If (fileFormName Is Nothing) OrElse (fileFormName.Length = 0) Then
fileFormName = "file"
End If
If (contenttype Is Nothing) OrElse (contenttype.Length = 0) Then
contenttype = "application/octet-stream"
End If
Dim postdata As String
postdata = "?"
If Not (querystring Is Nothing) Then
For Each key As String In querystring.Keys
postdata += key + "=" + querystring.Get(key) + "&"
Next
End If
Dim uri As Uri = New Uri(url + postdata)
Dim boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
Dim webrequest As HttpWebRequest = CType(Net.WebRequest.Create(uri), HttpWebRequest)
webrequest.CookieContainer = cookies
webrequest.ContentType = "audio/x-flac; rate=16000"
webrequest.Method = "POST"
Dim sb As StringBuilder = New StringBuilder
sb.Append("--")
sb.Append(boundary)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Disposition: form-data; name=""")
sb.Append(fileFormName)
sb.Append("""; filename=""")
sb.Append(IO.Path.GetFileName(uploadfilename))
sb.Append("""")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Type: ")
sb.Append(contenttype)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Dim postHeader As String = sb.ToString
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "--" + boundary + "" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Dim fileStreama As FileStream = New FileStream(uploadfilename, FileMode.Open, FileAccess.Read)
Dim length As Long = postHeaderBytes.Length + fileStreama.Length + boundaryBytes.Length
webrequest.ContentLength = length
Dim requestStream As Stream = webrequest.GetRequestStream
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
Dim sendBuffer(Math.Min(4096, fileStreama.Length)) As Byte
Dim bytesRead As Integer = 0
Do
bytesRead = fileStreama.Read(sendBuffer, 0, sendBuffer.Length)
If bytesRead = 0 Then Exit Do
requestStream.Write(sendBuffer, 0, bytesRead)
Loop
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim responce As WebResponse = webrequest.GetResponse
Dim s As Stream = responce.GetResponseStream
Dim sr As StreamReader = New StreamReader(s)
Return sr.ReadToEnd
sr.Dispose()
s.Dispose()
fileStreama.Dispose()
requestStream.Dispose()
webrequest.Abort()
responce.Close()
End Function
The function WORKS (Thankgod) but whenever I want to clear up (i.e. delete the audio file that is located in the c:) it just hangs and nothing happens...
Below is my code that executes on the formclosing event....
Private Sub Form1_Close(sender As System.Object, e As System.EventArgs) Handles MyBase.FormClosing
Dim di As New IO.DirectoryInfo("c:\")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
For Each dra In diar1
If dra.Name.Contains("record.") Then
dra.Delete()
End If
Next
End Sub
As you probably may be able to see from the function I HAVE TRIED TO REMOVE ALL THE STREAMS AND CLOSE THEM SO THE FILE IS NOT BEING ACCESSED
BUT it still hangs and when I try manually delete it... it tells me it is being used by another process (which is my program) - (I use ffmpeg to convert the .wav to .flac file but that does not cause any problems)....
What am I doing wrong...
Have I missed the closing of some stream or something.
By the way the uploadfilename string is c:\record.flac (just for your information - I dont think it will help)
Your function is calling Return BEFORE disposing of the file stream. This means that your Dispose call is never fired.. and the stream holds onto a file reference.
I Agree with Boo that the return before the dispose probably is the cause. So the solution would be to store the result of sr.ReadToEnd in a variable, close the streams and then return the var.
But a better solution would be to use the Using statement (http://msdn.microsoft.com/en-us/library/htd05whh.aspx) on every class that you have to call .Dispose() on (aka classes that implement IDisposable).
This gives clearer code because you can easily see what resources are in use where in your code. Also less buggy code as .NET ensures that everything is disposed once you leave the scope of the using block.
I am currently developing an application using VB.NET in which I am using the REST WebServices. I have been able to do the basics with REST, however, I have not been able to add an attachment (more specifically upload a file, using REST which gets attached). I have done extensive research online, but so far I have not been able to find any working examples in VB.NET. To actually upload the data I use System.Net.WebClient. The following VB.NET code does the important work:
Dim Client As New System.Net.WebClient
Dim postBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(postString)
Client.UploadData(URL, "POST", postBytes)
A simplified version of my URL is as follows:
"../REST/1.0/ticket/" + ticketNumber + "/comment?user=" + userName + "&pass=" + password
Finally, an example of the content that I post is:
postString = "content=Text: RT Test" + vbLf + "Action: Comment" + vbLf + "Attachment: examplefile.jpg" + vbLf + "attachment_1="
As you can see, the postString is converted to bytes and then uploaded to the server. However, I do not know where or how I should be posting the raw attachment itself. The documentation for the service we are specifically using states to use a variable "attachment_1," which I added to the postString variable, but I am not sure what the next step should be. Should the file be converted into bytes and appended to the postBytes variable? I attempted something like this but I received an error saying that no attachment was found for examplefile.jpg.
Thanks for your help!
We could not use Client.UploadData(...) and had to convert the entire post to bytes, starting with the POST fields before the attachment, then the attachment itself, and finally the remainder of the POST fields.
Public Sub AddAttachmentToRT(ByVal url As String, ByVal fileName As String, ByVal filePath As String)
Dim dataBoundary As String = "--xYzZY"
Dim request As HttpWebRequest
Dim fileType As String = "image/jpeg" 'Will want to extract this to make it more generic from the uploaded file.
'Create a POST web request to the REST interface using the passed URL
request = CType(WebRequest.Create(url), HttpWebRequest)
request.ContentType = "multipart/form-data; boundary=xYzZY"
request.Method = "POST"
request.KeepAlive = True
'Write the request to the requestStream
Using requestStream As IO.Stream = request.GetRequestStream()
'Create a variable "attachment_1" in the POST, specify the file name and file type
Dim preAttachment As String = dataBoundary + vbCrLf _
+ "Content-Disposition: form-data; name=""attachment_1""; filename=""" + fileName + """" + vbCrLf _
+ "Content-Type: " + fileType + vbCrLf _
+ vbCrLf
'Convert this preAttachment string to bytes
Dim preAttachmentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(preAttachment)
'Write this preAttachment string to the stream
requestStream.Write(preAttachmentBytes, 0, preAttachmentBytes.Length)
'Write the file as bytes to the stream by passing its exact location
Using fileStream As New IO.FileStream(Server.MapPath(filePath + fileName), 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
'Create a variable named content in the POST, specify the attachment name and comment text
Dim postAttachment As String = vbCrLf _
+ dataBoundary + vbCrLf _
+ "Content-Disposition: form-data; name=""content""" + vbCrLf _
+ vbCrLf _
+ "Action: comment" + vbLf _
+ "Attachment: " + fileName + vbCrLf _
+ "Text: Some description" + vbCrLf _
+ vbCrLf _
+ "--xYzZY--"
'Convert postAttachment string to bytes
Dim postAttachmentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(postAttachment)
'Write the postAttachment string to the stream
requestStream.Write(postAttachmentBytes, 0, postAttachmentBytes.Length)
End Using
Dim response As Net.WebResponse = Nothing
'Get the response from our REST request to RT
'Required to capture response, without this Try-Catch attaching will fail
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
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()
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub