上传对象到谷歌云存储桶在c#
答
我发现这个基本操作并不像你所期望的那么简单。 Google关于它的Storage API的文档缺乏有关在C#(或任何其他.NET语言)中使用它的信息。搜索“如何上传文件到谷歌云存储在C#”并没有完全帮助我,所以这里有一些意见我工作的解决方案:
准备:
您需要在您的Google Developers Console中创建OAuth2帐户 - 转至项目/ API & auth/Credentials。
复制客户端ID &客户端密码到您的代码。您还需要您的项目名称。
代码(它假定您已经通过的NuGet添加Google.Apis.Storage.v1):
首先,您需要授权您的要求:
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, "[email protected]", cts.Token);
有时您可能还希望通过以下方式刷新授权令牌:
await userCredential.RefreshTokenAsync(cts.Token);
您还需要创建存储服务:
var service = new Google.Apis.Storage.v1.StorageService();
现在您可以向Google Storage API发送请求。 让我们先从创建一个新的水桶:
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();
它完成。现在,您可以发送一个请求,让所有的桶的列表:
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();
}
}
和BAM!新文件将显示在您选择的存储区内的Google Developers Console中。
答
你会很高兴知道它仍然在2016年... 我是谷歌搜索使用像“谷歌gcp C#上传图像”的花式关键词,直到我只是普通的问题:“我如何上传图片到谷歌存储桶使用C#“...和我在这里。我删除了用户凭证中的.Result
,这是我为之工作的最终编辑。
// ******
static string bucketForImage = ConfigurationManager.AppSettings["testStorageName"];
static string projectName = ConfigurationManager.AppSettings["GCPProjectName"];
string gcpPath = Path.Combine(Server.MapPath("~/Images/Gallery/"), uniqueGcpName + ext);
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = ConfigurationManager.AppSettings["GCPClientID"];
clientSecrets.ClientSecret = ConfigurationManager.AppSettings["GCPClientSc"];
var scopes = new[] { @"https://www.googleapis.com/auth/devstorage.full_control" };
var cts = new CancellationTokenSource();
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, ConfigurationManager.AppSettings["GCPAccountEmail"], cts.Token);
var service = new Google.Apis.Storage.v1.StorageService();
var bucketToUpload = bucketForImage;
var newObject = new Google.Apis.Storage.v1.Data.Object()
{
Bucket = bucketToUpload,
Name = bkFileName
};
FileStream fileStream = null;
try
{
fileStream = new FileStream(gcpPath, FileMode.Open);
var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "image/"+ ext);
uploadRequest.OauthToken = userCredential.Token.AccessToken;
await uploadRequest.UploadAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
// ******
Upvote for for out the Object nature:new Google.Apis.Storage.v1.Data.Object – swissben 2018-03-08 12:39:16