0

我在 C# .Net 中工作,我希望能够将图像上传到 Google Drive 中创建的文件夹。请看下面的代码。使用此代码,我可以分别制作文件夹并上传图像,但我想编写代码以在创建的文件夹中上传图像

Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = "My first folder";
body.Description = "document description";
body.MimeType = "application/vnd.google-apps.folder";

// service is an authorized Drive API service instance
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(body).Fetch();

Google.Apis.Drive.v2.Data.File body1 = new Google.Apis.Drive.v2.Data.File();
body1.Title = "My first folder";
body1.MimeType = "image/jpeg";

//------------------------------------------

byte[] byteArray = System.IO.File.ReadAllBytes("Bluehills.jpg");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/jpeg");
request.Upload();

Google.Apis.Drive.v2.Data.File file1 = request.ResponseBody;
Console.WriteLine("File id: " + file1.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
4

1 回答 1

3

要在特定文件夹中插入文件,请在文件的 parents 属性中指定正确的 ID

https://developers.google.com/drive/folder

所以file.Id用作的父母body

编辑很难看到哪个是文件夹和哪个文件,因为fileandfile1bodyandbody1但我相信它是 file1.id 应该是 body1 的父级

编辑 2

if (!String.IsNullOrEmpty(file1.id)) {
    body1.Parents = new List<ParentReference>()
       { new ParentReference() {Id = file1.id} };
}

编辑3 完整代码:

Google.Apis.Drive.v2.Data.File folder = new Google.Apis.Drive.v2.Data.File();
folder.Title = "My first folder";
folder.Description = "folder document description";
folder.MimeType = "application/vnd.google-apps.folder";

// service is an authorized Drive API service instance
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(folder).Fetch();

Google.Apis.Drive.v2.Data.File theImage = new Google.Apis.Drive.v2.Data.File();
theImage.Title = "My first image";
theImage.MimeType = "image/jpeg";
theImage.Parents = new List<ParentReference>()
   { new ParentReference() {Id = file.Id} };

byte[] byteArray = System.IO.File.ReadAllBytes("Bluehills.jpg");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

FilesResource.InsertMediaUpload request = service.Files.Insert(theImage, stream, "image/jpeg");
request.Upload();

Google.Apis.Drive.v2.Data.File imageFile = request.ResponseBody;
Console.WriteLine("File id: " + imageFile.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
于 2012-10-23T09:59:45.270 回答