繁体   English   中英

Google云存储上传无法与C#API一起使用

[英]Google cloud storage upload not working with C# API

我正在尝试通过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();

想要执行此操作的任何人,我都会为您提供帮助,因为我不希望您花一天时间挠头,所以这里是您的操作方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM