我想使用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上的项目名称。
这是否应该转到云端硬盘的根文件夹?
此外,如果我们可以解决这个问题,我想进行后续操作并将其保存到特定的文件夹。
原来这是一个简单的解决方法。显然,我从中获得此解决方案的网站缺少上传行。因此,在创建上传请求后,您需要告诉它上传。
Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
UploadRequest.Upload()