如何使用googleapi将媒体文件上传到我的谷歌硬盘



嘿,我正试图使用谷歌api服务将某些媒体文件上传到我的谷歌驱动器,有人能告诉我如何做到吗?在我之前的问题中,我已经给出了getservice和clientservice的代码,你可以参考,谢谢

将文件上传到Google驱动器相当困难。

  1. 授权用户
  2. 创建文件元数据
  3. 上传文件数据本身

我有几个关于这个主题的教程和一个YouTube视频,这应该会让你开始。如何使用C#.net 将文件上传到Google Drive

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Upload;
Console.WriteLine("Hello, World!");
// Installed file credentials from google developer console.
const string credentialsJson = @"C:DevelopmentFreeLanceGoogleSamplesCredentialscredentials.json";
// used to store authorization credentials.
var userName = "user";
// scope of authorization needed from the user
var scopes = new[] { DriveService.Scope.Drive };
// file to upload
var filePath = @"C:DevelopmentFreeLanceGoogleSamplesDataimage.png";
var fileName = Path.GetFileName(filePath);
var folderToUploadTo = "1hwRZWAi-OznYGL51Yx9BJmDp5Ayips16";

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(credentialsJson).Secrets,
scopes,
userName,
CancellationToken.None).Result;

// Create the  Drive service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Daimto Drive upload Quickstart"
});

// Upload file photo.jpg on drive.
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string>() { folderToUploadTo }
};
var fsSource = File.OpenRead(filePath);
// Create a new file, with metadatafileName and stream.
var request = service.Files.Create(fileMetadata, fsSource, "image/jpeg");
request.Fields = "id";
var results = await request.UploadAsync(CancellationToken.None);
if (results.Status == UploadStatus.Failed)
{
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// the file id of the new file we created
var fileId = request.ResponseBody?.Id;
Console.WriteLine($"fileId {fileId}");
Console.ReadLine();