使用 chilkat 从 Web 文件选择器将文件上传到 Google 驱动器

Upload file to Google Drive from web file chooser using chilkat

我正在 Xojo 中开发一个 Web 应用程序,我使用 Chilkat 插件来管理 Google Drive 云,但我对使用此插件将文件上传到 Google 云有点迷茫。 在我的 Web 应用程序中,我添加了一个文件 select 或(到 select 一个 excel 文件)并添加了一个执行上传方法的按钮。我基于 Chilkat 自己网站上的一个示例,该网站具有以下代码:

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"))

问题出在这部分代码:

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

我不知道如何加载selected文件的路径,因为我不知道它(它必须是浏览器的临时路径)。

更新:(2021/08/31)

我已经设法通过 javascript 将文件直接上传到 Google 云端硬盘,但我不知道该脚本是否适合在 Chilkat 中工作。马特,你怎么看?

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)

我仍然不知道如何从文件选择器输入 selected 文件的临时路径。在javascript我用过这段代码

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

它有效,但是...在 chilkat 中呢?

有人可以帮帮我吗?

非常感谢。

此致,

沃迪亚姆

您的 Xojo 代码 运行 在网络服务器上,而不是在浏览器中。如果您希望从客户端计算机(浏览器运行的地方)上传,您只需使用 HTML 表单让浏览器发送包含文件的 multipart/form-data 请求。您将在服务器端编写代码来接收 multipart/form-data 请求。例如,在 C# 中可能会这样做:https://www.chilkatsoft.com/p/p_534.asp