1

我想通過C#API將簡單圖片上傳到Google雲端存儲。它似乎成功了,但我沒有看到我的Google雲存儲桶中有任何東西。Google雲端存儲上傳不適用於C#API

的代碼,我到目前爲止有:

Google.Apis.Services.BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer(); 
init.ApiKey = "@@[email protected]@"; 
init.ApplicationName = "@@[email protected]@"; 

Google.Apis.Storage.v1.StorageService ss = new Google.Apis.Storage.v1.StorageService(init); 

var fileobj = new Google.Apis.Storage.v1.Data.Object() 
{ 
    Bucket = "images", 
        Name = "some-file-" + new Random().Next(1, 666) 
}; 

Stream stream = null; 
stream = new MemoryStream(img); 

Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload insmedia; 
insmedia = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(ss, fileobj, "images", stream, "image/jpeg"); 
insmedia.Upload(); 
response.message = img.Length.ToString(); 

回答

7

任何人要做到這一點,我會幫助你,因爲我不想讓你花一天時間所以在這裏抓你的頭是怎麼了做這個。

首先創建一個「服務帳戶」類型的憑據,這將給你與P12擴展私鑰保存在某個地方,你可以在你的服務器上引用。

現在做到這一點:

String serviceAccountEmail = "YOUR SERVICE EMAIL HERE"; 

var certificate = new X509Certificate2(@"PATH TO YOUR p12 FILE HERE", "notasecret", X509KeyStorageFlags.Exportable); 

ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail) 
    { 
     Scopes = new[] { Google.Apis.Storage.v1.StorageService.Scope.DevstorageFullControl } 
    }.FromCertificate(certificate)); 

Google.Apis.Storage.v1.StorageService ss = new Google.Apis.Storage.v1.StorageService(new Google.Apis.Services.BaseClientService.Initializer() 
{ 
    HttpClientInitializer = credential, 
    ApplicationName = "YOUR APPLICATION NAME HERE", 
}); 

var fileobj = new Google.Apis.Storage.v1.Data.Object() 
{ 
    Bucket = "YOUR BUCKET NAME HERE", 
    Name = "file" 
}; 

Stream stream = null; 
stream = new MemoryStream(img); 

Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload insmedia; 
insmedia = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(ss, fileobj, "YOUR BUCKET NAME HERE", stream, "image/jpeg"); 
insmedia.Upload(); 
+0

創建服務帳戶在阿比和驗證您的開發人員控制檯 - >憑證 – Saumil 2014-11-22 18:55:33

相關問題