【问题标题】:Google cloud storage upload not working with C# API谷歌云存储上传不适用于 C# API
【发布时间】:2014-11-22 04:56:19
【问题描述】:

我正在尝试通过 C# API 将简单图像上传到 Google 云存储。它似乎成功了,但我在我的 Google 云存储桶中看不到任何内容。

我目前的代码:

Google.Apis.Services.BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer();
init.ApiKey = "@@myapikey@@";
init.ApplicationName = "@@myapplicationname@@";

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();

【问题讨论】:

    标签: c# google-api google-cloud-storage google-api-dotnet-client


    【解决方案1】:

    任何想要这样做的人我都会帮助你,因为我不想让你花一天时间摸不着头脑,所以这里是你如何做到这一点的。

    首先创建一个“服务帐户”类型的凭据,它将为您提供一个带有 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();
    

    【讨论】:

    • Creating Service Account 位于开发者控制台的 Api & Auth -> Credentials 下
    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2020-09-23
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多