Google cloud storage upload not working with C# API

隐身守侯 提交于 2019-12-08 13:07:41

Anyone looking to do this I'm going to help you out since I don't want you to spend a day scratching your heads so here is how you do this.

First of all create a "Service Account" type credentials which will give you a private key with p12 extension save this somewhere you can reference on your server.

Now do this:

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!