Как загрузить файл .txt на диск Google, используя VB.net? - PullRequest
0 голосов
/ 04 апреля 2019

Примечание. На самом деле пытается загрузить файл .bak, чтобы mimetype был другим.
I Я изменил mimetype на обычный / text для .txt, но проблема та же, что показана ниже.
Я пытаюсь загрузить файл .bak из моего приложения vb.net.
Я пытаюсь загрузить его в определенную папку.

Я пробовал Google auth v2 иv3.
При запросе на загрузку все работает нормально.Даже данные отправляются с моего компьютера (видно из скорости отправки в диспетчере задач), но файл фактически не загружается, и я ничего не получаю в ответном окне сообщения.

Ниже приведены коды, которые я пробовал.

 Private Sub CreateService()
    Dim ClientID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    Dim Secret = "xxxxxxxxxxxxxxxxxxxxxxx"

    Dim uc As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientID, .ClientSecret = Secret}, {Google.Apis.Drive.v3.DriveService.Scope.Drive}, "user", CancellationToken.None).Result
    service2 = New Google.Apis.Drive.v2.DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = uc, .ApplicationName = "myprojectGDriveApi"})
    service3 = New Google.Apis.Drive.v3.DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = uc, .ApplicationName = "myprojectGDriveApi"})
End Sub

Через Google auth V2,

 Private Sub Uploadfile2(filepath As String)
    If service2.ApplicationName <> "myprojectGDriveApi" Then CreateService()
  ''-----------------------------------UPLOADS A FILE--------------------------------------
'----------------------------Getting Folder ID-----------------------------
    Dim findrootid = New File() With {
        .Title = "NSQLBACKUP",
        .MimeType = "application/vnd.google-apps.folder"
    }
    Dim findrequest As Google.Apis.Drive.v2.FilesResource.ListRequest = service2.Files.List

    Dim list1 As FileList = findrequest.Execute()


    Dim FolderID As String = ""

    For Each item As File In list1.Items
        If item.MimeType = "application/vnd.google-apps.folder" Then
            If item.Title = "NSQLBACKUP" Then
                item.Id = FolderID
                Exit For
            End If
        End If
    Next

    Dim myfile As New File()
    myfile.Title = "LOLBACKUP"
    myfile.OriginalFilename = System.IO.Path.GetFileName(filepath)
    myfile.Description = "BackUP file"
    myfile.FileExtension = ".bak"
    myfile.MimeType = "application/octet-stream"
    myfile.Id = FolderID
    Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(filepath)
    Dim stream As New System.IO.MemoryStream(ByteArray)
    Dim uploadrequest As Google.Apis.Drive.v2.FilesResource.InsertMediaUpload = service2.Files.Insert(myfile, stream, myfile.MimeType)
    uploadrequest.Upload()
    Dim file As Google.Apis.Drive.v2.Data.File = uploadrequest.ResponseBody
    MsgBox(uploadrequest.ResponseBody)    '------- I get nothing here. Like blank msgbox Pops Up.
End Sub

Через Google Auth V3

 Public Function UploadFile3(service As Google.Apis.Drive.v3.DriveService, FilePath As String) As Google.Apis.Drive.v3.Data.File
    If service3.ApplicationName <> "myprojectGDriveApi" Then CreateService()
    If (System.IO.File.Exists(FilePath)) Then
        Dim body As New Google.Apis.Drive.v3.Data.File()
        body.Name = System.IO.Path.GetFileName(FilePath)
        body.Description = "BackUP file"
        body.FileExtension = ".bak"
        body.MimeType = "application/octet-stream"



        Dim findrequest As Google.Apis.Drive.v3.FilesResource.ListRequest = service3.Files.List
        Dim list1 As Google.Apis.Drive.v3.Data.FileList = findrequest.Execute


        Dim s As String = ""

        For Each item As Google.Apis.Drive.v3.Data.File In list1.Files
            If item.MimeType = "application/vnd.google-apps.folder" Then
                If item.Name = "NSQLBACKUP" Then
                    body.Id = item.Id.ToString
                    Exit For
                End If
            End If
        Next


        'Dim plist As List(Of String) = New List(Of String)           
        'plist.Add(s)                                        'Set parent folder
        'body.Parents = plist




        'files content
        Dim byteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
        Dim stream As New System.IO.MemoryStream(byteArray)
        Try
            Dim request As Google.Apis.Drive.v3.FilesResource.CreateMediaUpload = service.Files.Create(body, stream, "application/octet-stream")
            request.Upload()
            MsgBox(request.ResponseBody)   '------- Get nothing here also.
            Return request.ResponseBody
        Catch e As Exception
            MsgBox("An error occurred: " + e.Message)
            Return Nothing
        End Try

    Else
        MsgBox("File does not exist: " + FilePath)
        Return Nothing
    End If
End Function

Данные загружаются.
Я пытался загрузить большойФайл .bak и диспетчер задач показывают увеличение скорости отправки на 20 Мбит / с на некоторое время.Но тело ответа ничего не дает как в auth v2, так и в v3.И гугл диск не содержит ничего (проверено через браузер)

1 Ответ

0 голосов
/ 08 апреля 2019

Хорошо, я решил это.Просто удалил строку body.FileExtension = ".bak" из Google Auth v3, и она начала работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...