2012-10-23 72 views
0

我在C#.Net中工作,我希望能夠將圖像上傳到Google Drive中創建的文件夾。請看下面的代碼。有了這個代碼,我能夠做的文件夾,並分別上傳圖片,但我想編寫代碼來在創建的文件夾將圖像上傳到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(); 

回答

3

上傳圖片插入特定文件夾中的文件,指定在文件的父母財產正確的ID

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

所以使用file.Id作爲body

編輯挺難看的是文件夾,因爲filefile1bodybody1該文件,但我相信它是這應該是body1的父file1.id

編輯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(); 
+0

感謝您通過運行此代碼回覆JP我收到錯誤'Google.Apis.Drive.v2.Data.File'不包含'id'的定義,也沒有接受第一個參數的擴展方法'id'可以找到類型'Google.Apis.Drive.v2.Data.File'(你是否缺少使用指令或程序集引用?) – user1740827

+0

感謝JP實際上有一個小的變化theImage.Parents = new List () {new ParentReference(){Id = file.Id}};在做了更改後,我們得到的輸出非常感謝 – user1740827

+0

我想從我的Google驅動器帳戶迭代文件夾的另一個問題,我只想使用OAUTH方法,因爲我是新的谷歌驅動器請幫助我等待回覆 – user1740827

相關問題