使用服务帐户将文件上传到谷歌商家中心生成的谷歌云存储桶中
本文关键字:谷歌 商家 存储 服务 文件 | 更新日期: 2023-09-27 18:30:07
我能够用以下代码将文件上传到Google云存储桶。我手动创建了bucket。
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帐户生成的bucket时,我遇到了这个问题。我使用了上面的代码,只需将bucket名称从设置->谷歌云存储更改为谷歌商家中心提供的值
var bucketToUpload = "merchantxxxxxxx";
此过程没有将文件上传到bucket(使用gsutil测试-bucket在我的项目中存在,但为空)。为什么我不能上传文件?
您的代码未授权访问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对象将设置ServiceAccountCreential.Token.AccessToken。
然后,当您创建上传请求时,您必须提供您获得的AccessToken:
var uploadRequest = new ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "text/plain");
uploadRequest.OauthToken = sac.Token.AccessToken;
最后呼叫:
uploadRequest.Upload();