Is there any class, library or some piece of code which will help me to upload files with HTTPWebrequest?
Edit 2:
I do not
I was looking to do file upload and add some parameters to a multipart/form-data request in VB.NET and not through a regular forms post. Thanks to @JoshCodes answer I got the direction I was looking for. I am posting my solution to help others find a way to perform a post with both file and parameters the html equivalent of what I try to achieve is : html
Due to the fact that I have to provide the apiKey and the signature (which is a calculated checksum of the request parameters and api key concatenated string), I needed to do it server side. The other reason I needed to do it server side is the fact that the post of the file can be performed at any time by pointing to a file already on the server (providing the path), so there would be no manually selected file during form post thus form data file would not contain the file stream.Otherwise I could have calculated the checksum via an ajax callback and submitted the file through the html post using JQuery. I am using .net version 4.0 and cannot upgrade to 4.5 in the actual solution. So I had to install the Microsoft.Net.Http using nuget cmd
PM> install-package Microsoft.Net.Http
Private Function UploadFile(req As ApiRequest, filePath As String, fileName As String) As String
Dim result = String.empty
Try
''//Get file stream
Dim paramFileStream As Stream = File.OpenRead(filePath)
Dim fileStreamContent As HttpContent = New StreamContent(paramFileStream)
Using client = New HttpClient()
Using formData = New MultipartFormDataContent()
''// This adds parameter name ("action")
''// parameter value (req.Action) to form data
formData.Add(New StringContent(req.Action), "action")
formData.Add(New StringContent(req.ApiKey), "apiKey")
For Each param In req.Parameters
formData.Add(New StringContent(param.Value), param.Key)
Next
formData.Add(New StringContent(req.getRequestSignature.Qualifier), "signature")
''//This adds the file stream and file info to form data
formData.Add(fileStreamContent, "file", fileName)
''//We are now sending the request
Dim response = client.PostAsync(GetAPIEndpoint(), formData).Result
''//We are here reading the response
Dim readR = New StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8)
Dim respContent = readR.ReadToEnd()
If Not response.IsSuccessStatusCode Then
result = "Request Failed : Code = " & response.StatusCode & "Reason = " & response.ReasonPhrase & "Message = " & respContent
End If
result.Value = respContent
End Using
End Using
Catch ex As Exception
result = "An error occurred : " & ex.Message
End Try
Return result
End Function