在c#中将对象上传到谷歌云存储桶

有人可以提供一个如何使用Google.Apis.Storage.v1将文件上传到c#中的google云存储的示例吗?

我发现这个基本操作并不像你想象的那样直截了当。 谷歌关于它的存储API的文档缺乏有关在C#(或任何其他.NET语言)中使用它的信息。 搜索“ 如何将文件上传到c#中google云端存储 ”并没有完全帮助我,所以这是我的工作解决方案,其中包含一些注释:

制备:

  1. 您需要在Google Developers Console中创建OAuth2帐户 – 转到Project / API和auth / Credentials。

  2. 将客户端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, "yourGoogle@email", 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中看到新文件。

这适用于Google.Cloud.Storage.V1 (不是Google.Apis.Storage.v1 ),但现在执行上传似乎更简单一些。 我从客户端库的“入门”说明开始创建服务帐户和存储桶,然后进行实验以了解如何上传图像。

我遵循的流程是:

  1. 注册 Google Cloud免费试用版
  2. 在Google Cloud中创建一个新项目(请记住项目名称\ ID以供日后使用)
  3. 创建项目所有者服务帐户 – 这将导致下载包含服务帐户凭据的json文件。 记住放置该文件的位置。
  4. 入门文档可以让您将JSON凭证文件的路径添加到名为GOOGLE_APPLICATION_CREDENTIALS的环境变量中 – 我无法通过提供的说明进行操作。 事实certificate它不是必需的,因为您可以将JSON文件读入字符串并将其传递给客户端构造函数。
  5. 我创建了一个空的WPF项目作为起点,并创建了一个容纳应用程序逻辑的ViewModel
  6. 安装Google.Cloud.Storage.V1 nuget包,它应该引入它需要的所有依赖项。

在代码上。

MainWindow.xaml

     

MainWindow.xaml.cs

 public partial class MainWindow { readonly ViewModel _viewModel; public MainWindow() { _viewModel = new ViewModel(Dispatcher); DataContext = _viewModel; InitializeComponent(); } void OnButtonClick(object sender, RoutedEventArgs args) { _viewModel.UploadAsync().ConfigureAwait(false); } } 

ViewModel.cs

 public class ViewModel { readonly Dispatcher _dispatcher; public ViewModel(Dispatcher dispatcher) { _dispatcher = dispatcher; ProgressBar = new ProgressBar {Height=30}; } public async Task UploadAsync() { // Google Cloud Platform project ID. const string projectId = "project-id-goes-here"; // The name for the new bucket. const string bucketName = projectId + "-test-bucket"; // Path to the file to upload const string filePath = @"C:\path\to\image.jpg"; var newObject = new Google.Apis.Storage.v1.Data.Object { Bucket = bucketName, Name = System.IO.Path.GetFileNameWithoutExtension(filePath), ContentType = "image/jpeg" }; // read the JSON credential file saved when you created the service account var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromJson(System.IO.File.ReadAllText( @"c:\path\to\service-account-credentials.json")); // Instantiates a client. using (var storageClient = Google.Cloud.Storage.V1.StorageClient.Create(credential)) { try { // Creates the new bucket. Only required the first time. // You can also create buckets through the GCP cloud console web interface storageClient.CreateBucket(projectId, bucketName); System.Windows.MessageBox.Show($"Bucket {bucketName} created."); // Open the image file filestream using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { ProgressBar.Maximum = fileStream.Length; // set minimum chunksize just to see progress updating var uploadObjectOptions = new Google.Cloud.Storage.V1.UploadObjectOptions { ChunkSize = Google.Cloud.Storage.V1.UploadObjectOptions.MinimumChunkSize }; // Hook up the progress callback var progressReporter = new Progress(OnUploadProgress); await storageClient.UploadObjectAsync( newObject, fileStream, uploadObjectOptions, progress: progressReporter) .ConfigureAwait(false); } } catch (Google.GoogleApiException e) when (e.Error.Code == 409) { // When creating the bucket - The bucket already exists. That's fine. System.Windows.MessageBox.Show(e.Error.Message); } catch (Exception e) { // other exception System.Windows.MessageBox.Show(e.Message); } } } // Called when progress updates void OnUploadProgress(Google.Apis.Upload.IUploadProgress progress) { switch (progress.Status) { case Google.Apis.Upload.UploadStatus.Starting: ProgressBar.Minimum = 0; ProgressBar.Value = 0; break; case Google.Apis.Upload.UploadStatus.Completed: ProgressBar.Value = ProgressBar.Maximum; System.Windows.MessageBox.Show("Upload completed"); break; case Google.Apis.Upload.UploadStatus.Uploading: UpdateProgressBar(progress.BytesSent); break; case Google.Apis.Upload.UploadStatus.Failed: System.Windows.MessageBox.Show("Upload failed" + Environment.NewLine + progress.Exception); break; } } void UpdateProgressBar(long value) { _dispatcher.Invoke(() => { ProgressBar.Value = value; }); } // probably better to expose progress value directly and bind to // a ProgressBar in the XAML public ProgressBar ProgressBar { get; } } 

你会很高兴地知道它在2016年仍然有用…我在谷歌搜索使用像“google gcp C#upload image”这样的花哨关键词,直到我只是简单地问了一个问题:“我如何上传图片到谷歌斗使用C#“……我在这里。 我删除了用户凭据中的.Result ,这是对我.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(); } } // ******