![](/img/trans.png)
[英]Google cloud storage bucket using service account in Json file from C#
[英]Upload file using Service Account to Google Cloud Storage bucket that was generated in Google Merchant Center
我可以使用以下代碼將文件上傳到Google Cloud Storage存儲桶。 我手動創建了存儲桶。
String serviceAccountEmail = "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com";
var certificate = new X509Certificate2(@"C:\...\projectname-xxxxxxxxxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
var scopes = new[] { @"https://www.googleapis.com/auth/devstorage.full_control" };
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
StorageService service = new StorageService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Shipment Feed",
});
var bucketToUpload = "bucket-created-by-me";
var newObject = new Google.Apis.Storage.v1.Data.Object()
{
Bucket = bucketToUpload,
Name = "ShipmentFeed.txt"
};
FileStream fileStream = null;
var path = @"C:\...\file.txt";
fileStream = new FileStream(path, FileMode.Open);
var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "text/plain");
uploadRequest.Upload();
現在,當我嘗試將文件上傳到Google Merchant Center生成的同一Google帳戶的存儲桶時,我遇到了問題。 我使用了上面的代碼,只需將存儲桶名稱更改為Google Merchant中心從“設置”->“ Google Cloud Storage”提供的值
var bucketToUpload = "merchantxxxxxxx";
此過程未將文件上傳到存儲桶(已通過gsutil測試-存儲桶在我的項目中存在,但為空)。 為什么我不能上傳文件?
您的代碼未授權訪問Google雲端存儲。 創建ServiceAccountCredential后,必須通過調用以下方法獲取訪問令牌:
ServiceAccountCredential sac = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
var cts = new CancellationToken();
var response = sac.RequestAccessTokenAsync(cts).Result;
如果響應為true ,則您的ServiceAccountCredential對象將設置ServiceAccountCredential.Token.AccessToken 。
然后,當您創建uploadRequest時,您必須提供獲得的AccessToken:
var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "text/plain");
uploadRequest.OauthToken = sac.Token.AccessToken;
最后調用:
uploadRequest.Upload();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.