在C#中将对象上传到Google云存储桶 [英] Uploading objects to google cloud storage buckets in c#
问题描述
有人可以提供一个示例,说明如何使用Google.Apis.Storage.v1将文件上传到c#中的Google云存储吗?
Can someone please provide an example of how to use Google.Apis.Storage.v1 for uploading files to google cloud storage in c#?
推荐答案
我发现此基本操作并不像您期望的那样简单。 Google缺乏有关其Storage API的文档,缺乏有关以C#(或任何其他.NET语言)使用它的信息。搜索 如何在C#中将文件上传到Google云存储并不能完全为我提供帮助,因此这是我的工作解决方案,并带有一些注释:
I found that this basic operation is not as straight forward as you might expect. Google's documentation about it's Storage API is lacking in information about using it in C# (or any other .NET language). Searching for 'how to upload file to google cloud storage in c#' didn't exactly help me, so here is my working solution with some comments:
准备工作:
Preparation:
-
您需要在Google Developers Console中创建OAuth2帐户-到项目/ API和
You need to create OAuth2 account in your Google Developers Console - go to Project/APIs & auth/Credentials.
复制客户端ID&客户密码的秘密。您还将需要您的项目名称。
Copy Client ID & Client Secret to your code. You will also need your Project name.
代码(假定您已经添加了Google.Apis .NuGet.Storage.v1):
首先,您需要授权请求:
First, you need to authorize your requests:
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = clientId;
clientSecrets.ClientSecret = clientSecret;
//there are different scopes, which you can find here https://cloud.google.com/storage/docs/authentication
var scopes = new[] {@"https://www.googleapis.com/auth/devstorage.full_control"};
var cts = new CancellationTokenSource();
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets,scopes, "yourGoogle@email", cts.Token);
有时您可能还想通过以下方式刷新授权令牌:
Sometimes you might also want to refresh authorization token via:
await userCredential.RefreshTokenAsync(cts.Token);
您还需要创建存储服务:
You also need to create Storage Service:
var service = new Google.Apis.Storage.v1.StorageService();
现在您可以向Google Storage API发出请求了。
让我们从创建新存储桶开始:
Now you can make requests to Google Storage API. Let's start with creating a new bucket:
var newBucket = new Google.Apis.Storage.v1.Data.Bucket()
{
Name = "your-bucket-name-1"
};
var newBucketQuery = service.Buckets.Insert(newBucket, projectName);
newBucketQuery.OauthToken = userCredential.Result.Token.AccessToken;
//you probably want to wrap this into try..catch block
newBucketQuery.Execute();
就可以了。现在,您可以发送请求以获取所有存储桶的列表:
And it's done. Now, you can send a request to get list of all of your buckets:
var bucketsQuery = service.Buckets.List(projectName);
bucketsQuery.OauthToken = userCredential.Result.Token.AccessToken;
var buckets = bucketsQuery.Execute();
最后一部分是上传新文件:
//enter bucket name to which you want to upload file
var bucketToUpload = buckets.Items.FirstOrDefault().Name;
var newObject = new Object()
{
Bucket = bucketToUpload,
Name = "some-file-"+new Random().Next(1,666)
};
FileStream fileStream = null;
try
{
var dir = Directory.GetCurrentDirectory();
var path = Path.Combine(dir, "test.png");
fileStream = new FileStream(path, FileMode.Open);
var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload,fileStream,"image/png");
uploadRequest.OauthToken = userCredential.Result.Token.AccessToken;
await uploadRequest.UploadAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
还有!新文件将显示在您选定的存储桶中的Google Developers Console中。
And bam! New file will be visible in you Google Developers Console inside of selected bucket.
这篇关于在C#中将对象上传到Google云存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!