如何在不打开浏览器窗口的情况下在Google云端硬盘v3中上传文件?

时间:2017-08-28 14:12:36

标签: c# google-maps-api-3 file-upload

我的应用程序出现以下问题: 我想将简单文件上传到谷歌驱动器,没有错误,但它似乎没有工作,因为没有上传文件。 我在谷歌启用了API,添加了

using Google.Apis.Drive.v3.Data;
using Google.Apis.Upload;

到我的项目,但我无法理解为什么它不起作用。 我尝试过谷歌提供的不同解决方案,但没有一个能正常运行。 为了获得所需信息,我使用

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Net; 
// If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/drive-dotnet-quickstart.json
    static string[] Scopes = { DriveService.Scope.DriveReadonly };
    static string ApplicationName = "Drive API .NET Quickstart";

    static void Main(string[] args)
    {
        UserCredential credential;
        WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;

        using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true), new LocalServerCodeReceiver()).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Drive API service.
       // new Google.Apis.Drive.v2.DriveService()
        var service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        // Define parameters of request.
        Google.Apis.Drive.v3.FilesResource.ListRequest listRequest = service.Files.List();
       // listRequest.PageSize = 10;
        listRequest.Fields = "nextPageToken, files(id, name)";

        //Upload File
        gUpload(service, @"C:\Users\xxx\test.txt"); //THIS DOES NOT WORK

        // List files.
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
        Console.WriteLine("Files:");
        if (files != null && files.Count > 0)
        {
            foreach (Google.Apis.Drive.v3.Data.File file in files)
            { //THIS WORKS FINE
                Console.WriteLine("{0} ({1})", file.OriginalFilename, file.Id);
            }
        }
        else
        {
            Console.WriteLine("No files found.");
        }

        Console.ReadLine();
    }

这将为我提供正确的凭据,并列出我的gDrive文件夹中包含的所有文件及其垃圾文件。

另一方面,添加文件而不是列出它们无论如何都不起作用:

    public static void TestUpload(string filePath, DriveService driveService)
    {
        if (System.IO.File.Exists(filePath.ToString()))
        {
            File body = new File();
            body.Name = System.IO.Path.GetFileName(filePath.ToString());
            body.Description = "Test Description";
            body.MimeType = "text/plain";
            byte[] byteArray = System.IO.File.ReadAllBytes(filePath);

            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            FilesResource.CreateMediaUpload request = driveService.Files.Create(body, stream, "text/plain");
            request.Upload();
            File file = request.ResponseBody; //returns null value
        }

    }

运行时没有任何错误,但请求为空且没有上传,我的其他一个trys也运行没有错误,但没有上传任何内容。

public static bool gUpload(Google.Apis.Drive.v3.DriveService service, string filePath)
    {

        string fileID = "0B-W1aRTTOB1QM3hPd0dOUFVObHM"; //random
        System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
        File fBody = new File { Name = "test.txt" };

        var r = service.Files.Update(fBody, fileID, stream, "application/octet-stream");
        r.ChunkSize = ResumableUpload.MinimumChunkSize;
        r.Resume();
        // UploadStatus.Completed
        return true;
    }

我希望有人能够就如何更改代码以使上传工作给我一个有效的答案。

最诚挚的问候 千斤顶

1 个答案:

答案 0 :(得分:1)

看起来你使用了错误的范围,它应该是DriveService.Scope.Drive(但它可能是多余的)。一旦更新范围列表,也不要忘记删除缓存的凭据。您可以查看范围here