首页 > 解决方案 > 如何使用 vb.net 在 Google Drive 上上传文件?

问题描述


我需要帮助将文件上传到 Google 云端硬盘。
一切正常,但在第一次试用时出现错误。
request.upload光标处调试期间不要等待(等待文件上传)并跳到下一行Dim responsefile As New Data.File,我在request.ResponseBody.
之后我运行函数光标实际上等待request.upload并成功上传文件。
我不知道实际发生了什么。我每次都检查数据,结果都是一样的。

Public Async Function UploadFile3(service As DriveService, FilePath As String) As Tasks.Task(Of Data.File)

        If service3.ApplicationName <> "netGDriveApi" Then CreateService()
            If IO.File.Exists(FilePath) Then
                Dim body As New Data.File()
                body.Name = IO.Path.GetFileName(FilePath)
                body.Description = "BackUP file"
                body.MimeType = "application/octet-stream"
                'body.FileExtension = ".bak"



                '-------------------------------------------------UPLOAD FILE PROCESS-------------------------------------------------------------

                Dim byteArray As Byte() = IO.File.ReadAllBytes(FilePath)
                Dim stream As New IO.MemoryStream(byteArray)
                Try
                    Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
                    Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
                    Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.


                    responsefile = request.ResponseBody

                    If IsNothing(responsefile) Then
                        MessageBox.Show("Try Again")
                    Else
                        MessageBox.Show(responsefile.Id.ToString)
                    End If

                Catch e As Exception
                    MessageBox.Show("An error occurred: " + e.Message)
                    Return Nothing
                End Try

            Else
                MessageBox.Show("FILE DOES NOT EXISTS." + FilePath)
                Return Nothing
            End If
End Function

标签: vb.netgoogle-drive-api

解决方案


request.UploadAsync()返回一个Task(Of IUploadProgress)。至少,您应该检查此任务的结果。它可能会为您提供有关问题原因的线索。

例如,在调试时,您可以执行以下操作:

Try
    Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)

    Dim Upload As IUploadProgress = Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.

    If Upload.Status <> UploadStatus.Completed Then
        Dim ex As Exception = Upload.Exception
        MessageBox.Show(ex.Message, "UploadAsync Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return Nothing
    Else
        MessageBox.Show(Upload.Status.ToString, "Upload Status:")
    End If

    Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
    responsefile = request.ResponseBody

始终检查方法返回的信息,并在生产代码中根据需要使用该信息。


推荐阅读