有没有一种方法可以将文件从远程URL上传到Google驱动器-C#

时间:2020-05-17 22:32:10

标签: c# .net google-drive-api google-api-dotnet-client

基本上,我在远程服务器上有一些要上传到Google驱动器的视频,而无需将其下载到客户端。只需直接将它们上传到Google驱动程序即可。我在此处阅读了google drive api .net documentation和有关stackoverflow的一些问题,但他们没有提到任何此类问题。至少在我读过的问题中。我正在.net框架Windows窗体应用程序上执行此操作。

1 个答案:

答案 0 :(得分:0)

要使上传正常进行,您需要将文件保存在运行代码的计算机上。您将必须先将它们下载到自己,然后再将它们上传到Google驱动器。

{
    // Create the service using the client credentials.
    var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "APP_NAME_HERE"
        });
    var uploadStream = new System.IO.FileStream("FILE_NAME",
                                                System.IO.FileMode.Open,
                                                System.IO.FileAccess.Read);
    // Get the media upload request object.
    InsertMediaUpload insertRequest = service.Files.Insert(
        new File
        {
            Title = "FILE_TITLE",
        },
        uploadStream,
        "image/jpeg");

    // Add handlers which will be notified on progress changes and upload completion.
    // Notification of progress changed will be invoked when the upload was started,
    // on each upload chunk, and on success or failure.
    insertRequest.ProgressChanged += Upload_ProgressChanged;
    insertRequest.ResponseReceived += Upload_ResponseReceived;

    var task = insert.UploadAsync();
    task.ContinueWith(t =>
        {
            // Remeber to clean the stream.
            uploadStream.Dispose();
        });
}

static void Upload_ProgressChanged(IUploadProgress progress)
{
    Console.WriteLine(progress.Status + " " + progress.BytesSent);
}

static void Upload_ResponseReceived(File file)
{
    Console.WriteLine(file.Title + " was uploaded successfully");
}