我需要帮助上传文件到Google Drive。一切工作正常,但在第一次试验中出现错误。在调试期间,在 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
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
总是检查方法返回的信息,并在生产代码中使用这些信息。
这一行 Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
. 问题就在这里。感谢@stevec给我指导错误。驱动器服务是service3,在上面一行中,它只是写了 service.Files.Create
. 所以实际的整改答案是 Dim request As FilesResource.CreateMediaUpload = service3.Files.Create(body, stream, body.MimeType)