谷歌云存储上传不适用于C#API

本文关键字:不适用 适用于 C#API 存储 谷歌 | 更新日期: 2023-09-27 18:31:40

我正在尝试通过C#API将一个简单的图像上传到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#API

任何想要这样做的人,我都会帮助你,因为我不希望你花一天时间挠头,所以这就是你如何做到这一点。

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