Google cloud storage upload does not work with C # API
I am trying to upload a simple image to google cloud storage via C # API. It seems to work, but I can't see anything in my google cloud.
The code I have so far:
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();
+1
source to share
1 answer
Anyone who wants to do this, I'm going to help you as I don't want you to spend the day scratching your heads, this is how you do it.
First of all, create a credential of type "Service Account" that will provide you with a private key with a p12 extension, save it somewhere you can refer to on your server.
Now do the following:
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();
+7
source to share