我在C#.Net工作,我希望能够将图片上传到Google云端硬盘中创建的文件夹。请看下面的代码。使用此代码,我可以单独创建文件夹和上传图像,但我想编写代码以在创建的文件夹中上传图像
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();
答案 0 :(得分:3)
要在特定文件夹中插入文件,请在文件的parents属性中指定正确的ID
https://developers.google.com/drive/folder
所以请使用file.Id
作为body
修改很难看出哪个是文件夹,哪个文件是file
和file1
以及body
和body1
但我是相信它是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();