2014-10-04 116 views

回答

6

我發現這個基本操作並不像你所期望的那麼簡單。 Google關於它的Storage API的文檔缺乏有關在C#(或任何其他.NET語言)中使用它的信息。搜索「如何上傳文件到谷歌雲存儲在C#」並沒有完全幫助我,所以這裏有一些意見我工作的解決方案:

準備:

  1. 您需要在您的Google Developers Console中創建OAuth2帳戶 - 轉至項目/ API & auth/Credentials。

  2. 複製客戶端ID &客戶端密碼到您的代碼。您還需要您的項目名稱。

代碼(它假定您已經通過的NuGet添加Google.Apis.Storage.v1):

首先,您需要授權您的要求:

var clientSecrets = new ClientSecrets(); 
clientSecrets.ClientId = clientId; 
clientSecrets.ClientSecret = clientSecret; 
//there are different scopes, which you can find here https://cloud.google.com/storage/docs/authentication 
var scopes = new[] {@"https://www.googleapis.com/auth/devstorage.full_control"}; 

var cts = new CancellationTokenSource(); 
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets,scopes, "[email protected]", cts.Token); 

有時您可能還希望通過以下方式刷新授權令牌:

await userCredential.RefreshTokenAsync(cts.Token); 

您還需要創建存儲服務:

var service = new Google.Apis.Storage.v1.StorageService(); 

現在您可以向Google Storage API發送請求。 讓我們先從創建一個新的水桶

var newBucket = new Google.Apis.Storage.v1.Data.Bucket() 
{ 
    Name = "your-bucket-name-1" 
}; 

var newBucketQuery = service.Buckets.Insert(newBucket, projectName); 
newBucketQuery.OauthToken = userCredential.Result.Token.AccessToken; 
//you probably want to wrap this into try..catch block 
newBucketQuery.Execute(); 

它完成。現在,您可以發送一個請求,讓所有的桶的列表:

var bucketsQuery = service.Buckets.List(projectName); 
bucketsQuery.OauthToken = userCredential.Result.Token.AccessToken; 
var buckets = bucketsQuery.Execute(); 

最後一部分是上傳新文件

//enter bucket name to which you want to upload file 
var bucketToUpload = buckets.Items.FirstOrDefault().Name; 
var newObject = new Object() 
{ 
    Bucket = bucketToUpload, 
    Name = "some-file-"+new Random().Next(1,666) 
}; 

FileStream fileStream = null; 
try 
{ 
    var dir = Directory.GetCurrentDirectory(); 
    var path = Path.Combine(dir, "test.png"); 
    fileStream = new FileStream(path, FileMode.Open); 
    var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject, 
    bucketToUpload,fileStream,"image/png"); 
    uploadRequest.OauthToken = userCredential.Result.Token.AccessToken; 
    await uploadRequest.UploadAsync(); 
} 
catch (Exception ex) 
{ 
    Console.WriteLine(ex.Message); 
} 
finally 
{ 
    if (fileStream != null) 
    { 
     fileStream.Dispose(); 
    } 
} 

和BAM!新文件將顯示在您選擇的存儲區內的Google Developers Console中。

1

你會很高興知道它仍然在2016年... 我是谷歌搜索使用像「谷歌gcp C#上傳圖像」的花式關鍵詞,直到我只是普通的問題:「我如何上傳圖片到谷歌存儲桶使用C#「...和我在這裏。我刪除了用戶憑證中的.Result,這是我爲之工作的最終編輯。

  // ****** 

    static string bucketForImage = ConfigurationManager.AppSettings["testStorageName"]; 
    static string projectName = ConfigurationManager.AppSettings["GCPProjectName"]; 

      string gcpPath = Path.Combine(Server.MapPath("~/Images/Gallery/"), uniqueGcpName + ext); 
      var clientSecrets = new ClientSecrets(); 
      clientSecrets.ClientId = ConfigurationManager.AppSettings["GCPClientID"]; 
      clientSecrets.ClientSecret = ConfigurationManager.AppSettings["GCPClientSc"]; 

      var scopes = new[] { @"https://www.googleapis.com/auth/devstorage.full_control" }; 
      var cts = new CancellationTokenSource(); 
      var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, ConfigurationManager.AppSettings["GCPAccountEmail"], cts.Token); 
      var service = new Google.Apis.Storage.v1.StorageService(); 
      var bucketToUpload = bucketForImage; 
      var newObject = new Google.Apis.Storage.v1.Data.Object() 
      { 
       Bucket = bucketToUpload, 
       Name = bkFileName 
      }; 

      FileStream fileStream = null; 
      try 
      { 
       fileStream = new FileStream(gcpPath, FileMode.Open); 
       var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject, 
       bucketToUpload, fileStream, "image/"+ ext); 
       uploadRequest.OauthToken = userCredential.Token.AccessToken; 
       await uploadRequest.UploadAsync(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
      finally 
      { 
       if (fileStream != null) 
       { 
        fileStream.Dispose(); 
       } 
      } 

      // ****** 
+0

Upvote for for out the Object nature:new Google.Apis.Storage.v1.Data.Object – swissben 2018-03-08 12:39:16