0

I am developing a web application in Xojo and I use the Chilkat plugin to manage the Google Drive cloud but I am a bit lost with uploading files to the Google cloud with this plugin. In my web application I have added a file selector (to select an excel file) and added a button that executes the upload method. I have based this on an example on Chilkat's own website which has the following code:

Dim success As Boolean
success = True

//  This example requires the Chilkat API to have been previously unlocked.
//  See Global Unlock Sample for sample code.

//  This example uses a previously obtained access token having permission for the
//  Google Drive scope.
//  See Get Google Drive OAuth2 Access Token

Dim gAuth As New Chilkat.AuthGoogle
gAuth.AccessToken = "GOOGLE-DRIVE-ACCESS-TOKEN"

Dim rest As New Chilkat.Rest

//  Connect using TLS.
Dim bAutoReconnect As Boolean
bAutoReconnect = True
success = rest.Connect("www.googleapis.com",443,True,bAutoReconnect)

//  Provide the authentication credentials (i.e. the access token)
success = rest.SetAuthGoogle(gAuth)

//  -------------------------------------------------------------------------
//  A multipart upload to Google Drive needs a multipart/related Content-Type
success = rest.AddHeader("Content-Type","multipart/related")

//  Specify each part of the request.

//  The 1st part is JSON with information about the file.
rest.PartSelector = "1"
success = rest.AddHeader("Content-Type","application/json; charset=UTF-8")

//  Construct the JSON that will contain the metadata about the file data to be uploaded...
Dim json As New Chilkat.JsonObject
success = json.AppendString("name","starfish.jpg")
success = json.AppendString("description","A picture of a starfish.")
success = json.AppendString("mimeType","image/jpeg")

//  To place the file in a folder, we must add a parents[] array to the JSON
//  and add the folder ID.
//  In a previous example (see Lookup Google Drive Folder ID
//  we showed how to find the folder ID for a folder in Google Drive.

//  Use the folder ID we already looked up..
Dim folderId As String
folderId = "1Fksv-TfA1ILii1YjXsNa1-rDu8Cdrg72"
Dim parents As Chilkat.JsonArray
parents = json.AppendArray("parents")
success = parents.AddStringAt(-1,folderId)

success = rest.SetMultipartBodyString(json.Emit())

//  The 2nd part is the file content, which will contain the binary image data.
rest.PartSelector = "2"
success = rest.AddHeader("Content-Type","image/jpeg")

Dim jpgBytes As New Chilkat.BinData
success = jpgBytes.LoadFile("qa_data/jpg/starfish.jpg")

//  Add the data to our upload
success = rest.SetMultipartBodyBd(jpgBytes)

Dim jsonResponse As String
jsonResponse = rest.FullRequestMultipart("POST","/upload/drive/v3/files?uploadType=multipart")
If (rest.LastMethodSuccess <> True) Then
    System.DebugLog(rest.LastErrorText)
    Return
End If

//  A successful response will have a status code equal to 200.
If (rest.ResponseStatusCode <> 200) Then
    System.DebugLog("response status code = " + Str(rest.ResponseStatusCode))
    System.DebugLog("response status text = " + rest.ResponseStatusText)
    System.DebugLog("response header: " + rest.ResponseHeader)
    System.DebugLog("response JSON: " + jsonResponse)
    Return
End If

success = json.Load(jsonResponse)

//  Show the full JSON response.
json.EmitCompact = False
System.DebugLog(json.Emit())

//  A successful response looks like this:
//  {
//    "kind": "drive#file",
//    "id": "0B53Q6OSTWYoldmJ0Z3ZqT2x5MFk",
//    "name": "starfish.jpg",
//    "mimeType": "image/jpeg"
//  }

//  Get the fileId:
System.DebugLog("fileId: " + json.StringOf("id"))

The problem is in this part of the code:

Dim jpgBytes As New Chilkat.BinData
success = jpgBytes.LoadFile("qa_data/jpg/starfish.jpg")

I don't know how to load the path of the selected file since I don't know it (it must be a temporary path of the browser).

Update: (2021/08/31)

I have managed with javascript to upload a file directly to Google Drive but I don't know if the script could be adapted to work in Chilkat. What do you think about this, Matt?

Var s As String
Var id_folder As String = "1lwDHPYPFetdrDcwND2g07AsmCSWIUIbY" 

s = ""
s = s + "Var input_file = $('#formFileLg')[0].files[0];"
s = s + "Var formData = new FormData();"
s = s + "formData.append('formFileLg', input_file, input_file.name);"
s = s + "formData.append('upload_file', true);"
s = s + "var metadata = {"
s = s + "name: input_file.name,"
s = s + "mimeType: input_file.name.type,"
s = s + "parents: ['"+id_folder+"']"
s = s + "};"

s = s + "formData.append( 'metadata', new Blob( [JSON.stringify( metadata )], {type: 'application/json'} ));"
s = s + "$.ajax({"
s = s + "type: 'POST',"
s = s + "beforeSend: function(request) {"
s = s + "request.setRequestHeader('Authorization', 'Bearer' + ' ' + '"+API_TOKEN+"');"
s = s + "},"
s = s + "url: 'https://www.googleapis.com/upload/drive/v3/files?access_token="+API_TOKEN+"',"
s = s + "dataType: 'json',"
s = s + "data:{"
s = s + "uploadType:'media'},"
s = s + "xhr: function () {"
s = s + "var myXhr = $.ajaxSettings.xhr();"
s = s + "if (myXhr.upload) {"
s = s + "}"
s = s + "return myXhr;"
s = s + "},"
s = s + "success: function (data) {"
s = s + "console.log(data);"
s = s + "},"
s = s + "error: function (error) {"
s = s + "console.log(error);"
s = s + "},"
s = s + "async: true,"
s = s + "data: formData,"
s = s + "cache: false,"
s = s + "contentType: false,"
s = s + "processData: false,"
s = s + "timeout: 60000"
s = s + "});"

Me.ExecuteJavaScript(s)

I still don't know how to enter the temporary path of the selected file from the file chooser. In javascript I have used this code

s = s + "Var input_file = $('#formFileLg')[0].files[0];"

and it works but... what about in chilkat?

Could someone help me, please?.

Thank you very much.

Best regards,

Wardiam

Wardiam
  • 127
  • 7

1 Answers1

0

Your Xojo code is running on the web server, not within the browser. If you wish to upload from the client machine (where the browser runs), you simply use an HTML form to let the browser send the multipart/form-data request containing the files. You would write code on the server-side to receive the multipart/form-data request. For example, this is what one might do in C#: https://www.chilkatsoft.com/p/p_534.asp

Chilkat Software
  • 1,405
  • 1
  • 9
  • 8
  • I understand your answer but I am looking for something that will allow me to directly upload files to Google Drive. I have updated my post with a javascript script that works for me (directly) but I don't know if it could be adapted for Chilkat. What do you think?. – Wardiam Aug 31 '21 at 18:48
  • If you put the access token in the Javascript, then I would think it's visible to anyone using your site, and thus somebody could take the access token and upload whatever they want to your Google Drive, or do whatever else was permitted by the scope used when you got the access token. – Chilkat Software Sep 01 '21 at 19:13
  • I hadn't thought about being able to see the javascript code, you may be right. If I used chilkat (if it could do the same thing) then, would the same thing happen?. Then I could only get around it by uploading the file to the server and uploading from there. Of course that means a significant delay. Would there be any intermediate solution?. – Wardiam Sep 01 '21 at 21:18
  • I've been reviewing the "Best Practices for Securely Use of API Keys" document and you're right, I neglected that part. But I have externalized the API key to an external file hosted on the server and also limited the use of the API to only the server IP this way it is more difficult to maliciously use the API. Following your advice, I have solved the security issue but you haven't answered me, do you think it would be possible to "adapt" the script to chilkat?. I feel more comfortable with your plugin and it seems more intelligible to me. Could you help me Matt?. Thanks – Wardiam Sep 02 '21 at 18:21
  • You can't run Chilkat within your browser because Chilkat is native (compiled) code. You can only run scripts (such as Javascript) on the client-side. Therefore, the only possibility is to upload to your server using standard HTTP upload, and then once on the server, upload to Google Drive. – Chilkat Software Sep 03 '21 at 12:48
  • You are absolutely right Matt. I'm going to try to convert my application to a server hosted web service and upload the files to the server and from there to the Google cloud. When I go to upload the files to the cloud I will try to use chilkat (now from a local file on the server). Thanks for your wisdom and patience ;-) – Wardiam Sep 04 '21 at 19:42