使用Visual Basic将文件上传到Google云端硬盘

时间:2019-10-02 18:08:02

标签: vb.net google-drive-api

我想使用Visual Basic桌面应用程序将文件上传到Google云端硬盘。该应用程序的主要目的是执行更多操作,但这是我需要添加的省时功能

我已经下载了NuGet for Google.Apis.Drive.v2,并添加了以下代码:

Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services

我有一个按钮可以调用我的代码:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    CreateService()
    UploadFile(myFile)
End Sub

然后我有创建服务和上载文件的代码:

Private Sub CreateService()

    Dim ClientId = "My ClientID copied from Google"
    Dim ClientSecret = "My Client Secret"   

    Dim MyUserCredential As UserCredential = _
    GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() _
    With {.ClientId = ClientId, .ClientSecret = ClientSecret}, _
    {DriveService.Scope.Drive}, "user", CancellationToken.None).Result 

    Service = New DriveService(New BaseClientService.Initializer() _
    With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "SiteVisitTool"})

End Sub

Private Sub UploadFile(FilePath As String)
    Me.Cursor = Cursors.WaitCursor
    If Service.ApplicationName <> "SiteVisitTool" Then CreateService()

    Dim TheFile As New Google.Apis.Drive.v2.Data.File
    TheFile.Title = "Deliverables"
    TheFile.Description = "Site Visit data for Google forms"
    TheFile.MimeType = "text/csv"

    Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
    Dim Stream As New System.IO.MemoryStream(ByteArray)

    Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)

    Me.Cursor = Cursors.Default
    MsgBox("Upload Finished")

End Sub

代码运行,我得到一个消息框,说明上传已完成。我已经检查了云端硬盘,但文件不存在。有时,系统会提示我输入我要使用的帐户,然后必须将其激活,但是我总是收到一条消息,提示它已上传。非常沮丧!

“ SiteVisitTool”是Google上的项目名称。

这是否应该转到云端硬盘的根文件夹?

此外,如果我们可以解决这个问题,我想进行后续操作并将其保存到特定的文件夹中。

1 个答案:

答案 0 :(得分:0)

事实证明这是一个简单的解决方法。显然,我从中获得此解决方案的网站缺少上传行。因此,在创建上传请求后,您需要告诉它上传。

docker exec -t -i -u root 8a3e4871ed64 /bin/bash

关于指定要上传到的文件夹,我在设置TheFile属性的位置添加了

Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
UploadRequest.Upload()