Upload File to Amazon S3 - amazon-s3

Let me explain my requirement..
I want to store files uploaded to my app (by clients) to Amazon S3..
File Size ~ 1-10 MB
However, the client interface has to be a REST API
provided by my application. Consequently, after parsing file upload (HTTP POST) request, my application must store the file in S3.
As a result, I have to store file temporarily on disk before uploading to S3..
Is there a workaround? Can I do away with temporary file store on my server.. Please let me know if I am not clear..
EDIT - Is it OK to get byte array from FileItem object and store it rather than the file itself..?

Your whole idea is to avoid I/O right ? you don't need to save the file before doing the upload, you could simple send the array of bytes to amazon REST API.
Here is my sample VB.NET code that do both upload and download:
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Imports System.Threading.Tasks
Module Module1
Sub Main()
Dim obj As New Program
obj.UploadFile()
'obj.DownloadFile() 'Download Example
End Sub
End Module
Class Program
Private Const KeyId As String = "yourkey"
Private Const AccessKey As String = "your/access"
Private Const S3Url As String = "https://s3.amazonaws.com/"
Public Sub DownloadFile()
Dim bucketName As String = "yourbucket"
Dim FileName As String = "file.png"
Dim timeStamp As String = String.Format("{0:r}", DateTime.UtcNow)
Dim stringToConvert As String = Convert.ToString((Convert.ToString((Convert.ToString("GET" & vbLf + vbLf + vbLf + vbLf + "x-amz-date:") & timeStamp) + vbLf + "/") & bucketName) + "/") & FileName
Dim ae = New UTF8Encoding()
Dim signature = New HMACSHA1() With { _
.Key = ae.GetBytes(AccessKey) _
}
Dim bytes = ae.GetBytes(stringToConvert)
Dim moreBytes = signature.ComputeHash(bytes)
Dim encodedCanonical = Convert.ToBase64String(moreBytes)
' Send the request
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(Convert.ToString((Convert.ToString("https://") & bucketName) + ".s3.amazonaws.com" + "/") & FileName), HttpWebRequest)
'request.ContentType = "application/octet-stream";
request.Headers.Add("x-amz-date", timeStamp)
request.Headers.Add("Authorization", "AWS " + KeyId + ":" + encodedCanonical)
request.Method = "GET"
' Get the response
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim ReceiveStream As Stream = response.GetResponseStream()
Console.WriteLine(response.StatusCode)
End Sub
Public Sub UploadFile()
Dim fileData = File.ReadAllBytes("C:\file.png")
Dim timeStamp As String = String.Format("{0:r}", DateTime.UtcNow)
Dim stringToConvert As String = (Convert.ToString("PUT" & vbLf + vbLf + "application/octet-stream" & vbLf + vbLf + "x-amz-acl:public-read" + vbLf + "x-amz-date:") & timeStamp) + vbLf + "/celso711/file.png"
'resource
Dim ae = New UTF8Encoding()
Dim signature = New HMACSHA1() With { _
.Key = ae.GetBytes(AccessKey) _
}
Dim bytes = ae.GetBytes(stringToConvert)
Dim moreBytes = signature.ComputeHash(bytes)
Dim encodedCanonical = Convert.ToBase64String(moreBytes)
Dim url = "https://bucket.s3.amazonaws.com/file.png"
Dim request = TryCast(WebRequest.Create(url), HttpWebRequest)
request.Method = "PUT"
request.Headers("x-amz-date") = timeStamp
request.Headers("x-amz-acl") = "public-read"
request.ContentType = "application/octet-stream"
request.ContentLength = fileData.Length
request.Headers("Authorization") = (Convert.ToString("AWS ") & KeyId) + ":" + encodedCanonical
Dim requestStream = request.GetRequestStream()
requestStream.Write(fileData, 0, fileData.Length)
requestStream.Close()
Using response = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader = New StreamReader(response.GetResponseStream())
Dim data = reader.ReadToEnd()
End Using
End Sub
End Class

Related

HttpClient Digest authentication VB.Net

I'm writing an .NET application that uses HttpClient to connect to the API and retrieve video.
The Documentation provided for "Cookie-based authentication" details the following to login:
Call GET /api/getNonce
In response you'll get a JSON object with realm and nonce (nonce is a session key for this user)
Calculate authentication hash auth_digest, using realm and nonce (see algorithm below)
Call and pass the "auth" parameter in the json request body GET /api/cookieLogin
Server will check authentication and set session cookies
Which then expands on "Calculating Authentication Hash" with the following steps:
Call GET /api/getNonce
In response you'll get a JSON object with realm and nonce
Translate user's username to the lower case
Check the required method ("GET" for HTTP GET requests, "POST" for HTTP POST
requests, "PLAY" for RTSP etc)
digest = md5_hex(user_name + ":" + realm + ":" + password)
partial_ha2 = md5_hex(method + ":")
simplified_ha2 = md5_hex(digest + ":" + nonce + ":" + partial_ha2)
auth_digest = base64(user_name + ":" + nonce + ":" + simplified_ha2)
Here auth_digest is the required authentication hash
I use this Article written in C# as a reference, converted it to VB.NET, change a little bit of code in it according to the requirement above and then implemented it into my program. But I always get an error like this
"The remote server returned an error: (403) Forbidden."
When I debug the program, the problem appears when reading DigestAuthFixer.vb class in GrabResponse Function on this line response = CType(request2.GetResponse(), HttpWebResponse) . I suspect that "auth_digest" didn't return the correct value so the web service to deny the request with a 403 error. My question is how to properly implement digest authentication using VB.Net ? Are there any standard methods or do I have to do it from scratch? Thanks in advance.
This is the code that I use to connect to the API and retrieve the video:
Download HTTPClient
Private Shared _host As String = "http://127.0.0.1:7001"
Private Shared _username As String = "user"
Private Shared _password As String = "password"
Dim auto As Boolean = False
Shared ReadOnly client As HttpClient = New HttpClient()
Public Async Function Download_HttpClient(ByVal cameraID As String _
, ByVal videoDT As String _
, ByVal duration As String _
, ByVal resolution As String _
, ByVal path As String) As Task(Of String)
Dim cookieContainer As New CookieContainer
Dim httpClientHandler As New HttpClientHandler
httpClientHandler.AllowAutoRedirect = True
httpClientHandler.UseCookies = True
httpClientHandler.CookieContainer = cookieContainer
Dim httpClient As New HttpClient(httpClientHandler)
Dim err As Boolean = False
Dim downloadFileName As String
'SET HTTPCLIENT HEADERS
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)")
'httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml")
httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+json,application/json")
httpClient.DefaultRequestHeaders.Add("Accept-Charset", "ISO-8859-1")
Dim downloadId As String = Nothing
Try
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 Or SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls
'GET USER RIGHTS
Dim login_url As String = _host + "/api/getNonce"
Dim login_parameter As String = "?user_name =" + _username + "&password=" + _password
Dim login_response As HttpResponseMessage = Await httpClient.GetAsync(login_url + login_parameter)
Dim login_contents As String = Await login_response.Content.ReadAsStringAsync()
'CALCULATE AUTHENTICATION HASH
Dim dir As String = "/dir/index.html"
Dim url As String = _host + "/api/getNonce"
Dim digest As NUI.DigestAuthFixer = New NUI.DigestAuthFixer(url, _username.ToLower, _password)
Dim auth As String = digest.GrabResponse(dir)
'CALL POST /api/cookieLogin
Dim client As HttpClient = New HttpClient
client.DefaultRequestHeaders.Accept.Add(New System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"))
Dim postData As New List(Of KeyValuePair(Of String, String))
postData.Add(New KeyValuePair(Of String, String)("auth_digest ", auth))
Dim content As New FormUrlEncodedContent(postData)
content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/x-runtime-guid")
Dim response As HttpResponseMessage = client.PostAsync(New Uri(_host + "/api/cookieLogin"), content).Result
If response.IsSuccessStatusCode Then
MsgBox("POST CookieLogin Successfully")
Else
MsgBox(response)
End If
Catch ex As Exception
MessageBox.Show("Invalid response from the server due to connection limitation or firewall blocking your request")
Return ex.ToString()
End Try
'CREATE DOWNLOAD URL
Dim download_url As String = _host + "/media/" + cameraID + ".mkv"
Dim download_param As String = "?pos=" + videoDT + "&duration=" + duration + "&resolution=" + resolution
Dim downloadFile As String = download_url + download_param
'GET REQUEST AND DOWNLOAD
Dim file_response = Await httpClient.GetAsync(downloadFile)
Dim file_header = file_response.Content.Headers.GetValues("Content-Disposition")
Dim temp_string() As String = file_header.ToArray()
temp_string = temp_string(0).Split("=")
downloadFileName = temp_string(1).Replace("""", "")
Try
Using fs As New FileStream(path & downloadFileName, FileMode.Create)
Await file_response.Content.CopyToAsync(fs)
End Using
Catch ex As Exception
MessageBox.Show("Directory does not exists, please manually change the folder target")
Return ex.ToString()
End Try
Return "Download successfully"
End Function
DigestAuthFixer.vb class
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.IO
Imports System.Net.Http
Namespace NUI
Public Class DigestAuthFixer
Private Shared _host As String
Private Shared _user As String
Private Shared _password As String
Private Shared _realm As String
Private Shared _nonce As String
Private Shared _qop As String
Private Shared _cnonce As String
Private Shared _cnonceDate As DateTime
Private Shared _nc As Integer
Public Sub New(ByVal host As String, ByVal user As String, ByVal password As String)
_host = host
_user = user
_password = password
End Sub
Private Function CalculateMd5Hash(ByVal input As String) As String
Dim inputBytes As Byte() = Encoding.GetEncoding("ISO-8859-1").GetBytes(input)
Dim hash = MD5.Create().ComputeHash(inputBytes)
Dim sb As New System.Text.StringBuilder()
For Each b In hash
sb.Append(b.ToString("x2"))
Next b
Return sb.ToString()
End Function
Private Function GrabHeaderVar(ByVal varName As String, ByVal header As String) As String
Dim regHeader = New Regex(String.Format("{0}=""([^""]*)""", varName))
Dim matchHeader = regHeader.Match(header)
If matchHeader.Success Then Return matchHeader.Groups(1).Value
Throw New ApplicationException(String.Format("Header {0} not found", varName))
End Function
Private Function GetDigestHeader(ByVal dir As String) As String
Dim digest = CalculateMd5Hash(_user.ToLower + ":" + _realm + ":" + _password)
Dim partial_ha2 = CalculateMd5Hash("GET" + ":")
Dim simplified_ha2 = CalculateMd5Hash(digest + ":" + _nonce + ":" + partial_ha2)
Dim auth_digest = (_user.ToLower + ":" + _nonce + ":" + simplified_ha2)
Return auth_digest
End Function
Public Function GrabResponse(ByVal dir As String) As String
Dim url = _host & dir
Dim uri = New Uri(url)
Dim request = CType(WebRequest.Create(uri), HttpWebRequest)
If Not String.IsNullOrEmpty(_cnonce) AndAlso DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0 Then
request.Headers.Add("Authorization", GetDigestHeader(dir))
End If
Dim response As HttpWebResponse
Try
response = CType(request.GetResponse(), HttpWebResponse)
Catch ex As WebException
If ex.Response Is Nothing OrElse (CType(ex.Response, HttpWebResponse)).StatusCode <> HttpStatusCode.Unauthorized Then Throw
Dim wwwAuthenticateHeader = ex.Response.Headers("WWW-Authenticate")
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader)
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader)
_qop = "auth"
_nc = 0
_cnonce = New Random().[Next](123400, 9999999).ToString()
_cnonceDate = DateTime.Now
Dim request2 = CType(WebRequest.Create(uri), HttpWebRequest)
request2.Headers.Add("Authorization", GetDigestHeader(dir))
response = CType(request2.GetResponse(), HttpWebResponse)
End Try
Dim reader = New StreamReader(response.GetResponseStream())
Return reader.ReadToEnd()
End Function
End Class
End Namespace

How to call the API POST method by passing the base64 image with the urlencoded in VB?

I'm trying to call the API post method by passing the image file (converting into base64 format).
I am able to call successfully in POSTMAN as per below:
But I'm unable to call in vb code and got the error message.
Below is my code in vb:
Function CallAPI(ByVal URL As String, ByVal Data As String) As String
Dim dataStream() As Byte = Encoding.UTF8.GetBytes(Data)
Dim request As String = (URL)
Dim webRequest As WebRequest = WebRequest.Create(request)
webRequest.Method = "POST"
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.ContentLength = dataStream.Length
Dim newStream As Stream = webRequest.GetRequestStream
' Send the data.
newStream.Write(dataStream, 0, dataStream.Length)
newStream.Close()
Dim Response As WebResponse = webRequest.GetResponse
Dim Reader As New StreamReader(Response.GetResponseStream)
Dim Results As String = Reader.ReadToEnd
Return Results
End Function
'Below is the code to convert the image file to base64 format:
Dim imgBase64 As String = ""
Dim imgBase64FilePath As String = ""
imgBase64FilePath = State.ApplicationSettings.WebPath().ToString() + "Photos\" + CStr(Fields.Item("EMPE_ID").Value) + "_" + epFields.GetValue("COMP_CODE").ToString().ToUpper() + ".jpg"
If helper.IsExists(imgBase64FilePath) Then
imgBase64 = ConvertFileToBase64(imgBase64FilePath)
End If
'I call the above function as per below:
Dim url = "http://" + deviceIP + "/face/create"
Dim data As String = "pass=" + devicePW + "&personId=" + CStr(Fields.Item("CARD_NO").Value) + "&faceId=" + CStr(Fields.Item("CARD_NO").Value) + "&imgBase64=" + imgBase64
Dim response As String = CallAPI(url, data)
Below is the error response:
{"code":"2000","msg":"200003, bad base-64","result":1,"success":false}
May I know which part is wrong?
Please advise me.
Thanks in Advance.

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

Google Drive Rest: convert does not work

I am using the G Drive REST endpoints (not .net client) to upload docx files through vb .net. My problem is that if even i declare the query parameter "convert" as true, the files are getting uploaded but they never auto-convert.
The first thing i do is to create a new file with POST and after that i upload the content with Put in the upload uri in a separate request.
it does not even work when i use the Google Playground to upload the docx files.
Public Shared Function UploadStream(fileStream As IO.Stream, filename As String, mimetype As String, target As String, accesstoken As String, Optional ConvertToGDoc As Boolean = False) As String
Try
Dim subject As String = ""
Dim doc As New Aspose.Words.Document
Dim docformat = Aspose.Words.FileFormatUtil.DetectFileFormat(fileStream) ' detect the format of the file Then 'check if the file is doc or docx
If docformat.LoadFormat = Aspose.Words.LoadFormat.Doc Or docformat.LoadFormat = Aspose.Words.LoadFormat.Docx Then 'check if the file is word document
doc = New Aspose.Words.Document(fileStream)
subject = doc.BuiltInDocumentProperties.Subject 'get the subject from the word file
If doc.BuiltInDocumentProperties.Subject = "" Then subject = "none"
Else
subject = "none" 'set the subject as none if the file is not word file
End If
Dim localmd5 = Files.MD5stream(fileStream)
Dim baseaddress = "https://www.googleapis.com/drive/v2/files?convert=" + ConvertToGDoc.ToString
Dim req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "POST"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
req.ContentType = "application/json"
Dim writer = New Newtonsoft.Json.Linq.JTokenWriter()
writer.WriteStartObject()
writer.WritePropertyName("title")
writer.WriteValue(filename)
writer.WritePropertyName("parents")
writer.WriteStartArray()
writer.WriteRawValue("{'id':'" + target + "'}")
writer.WriteEndArray()
writer.WritePropertyName("properties")
writer.WriteStartArray()
writer.WriteRawValue("{'key':'Subject','value':'" + subject + "'},{'key':'MD5','value':'" + localmd5 + "'},{'key':'Author','value':''}")
writer.WriteEndArray()
writer.WriteEndObject()
Dim bodybytes = Text.Encoding.UTF8.GetBytes(writer.Token.ToString)
req.ContentLength = bodybytes.Length
Dim requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
Dim resp As System.Net.HttpWebResponse = req.GetResponse()
Dim response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Dim json As Newtonsoft.Json.Linq.JObject
json = Newtonsoft.Json.Linq.JObject.Parse(response)
Dim fileId = json.SelectToken("id").ToString()
baseaddress = "https://www.googleapis.com/upload/drive/v2/files/" + fileId + "?uploadType=media&convert=" + ConvertToGDoc.ToString
req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "Put"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
bodybytes = General.GetStreamAsByteArray(fileStream)
req.ContentLength = bodybytes.Length
req.ContentType = mimetype
requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
resp = req.GetResponse()
response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Return fileId
Catch ex As Exception
Return Nothing
End Try
End Function
Shared Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
stream.Position = 0
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()
ReDim Preserve fileData(fileData.Length - 2)
Return fileData
End Function
Public Shared Function MD5stream(ByVal File_stream As IO.Stream, Optional ByVal Seperator As String = Nothing) As String
Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim Hash() As Byte = MD5.ComputeHash(File_stream)
Return Replace(BitConverter.ToString(Hash), "-", Seperator)
End Using
End Function
Had anyone else the same problem?

Attachments using REST WebService and VB.NET

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