• <tfoot id='58x2e'></tfoot>
    <i id='58x2e'><tr id='58x2e'><dt id='58x2e'><q id='58x2e'><span id='58x2e'><b id='58x2e'><form id='58x2e'><ins id='58x2e'></ins><ul id='58x2e'></ul><sub id='58x2e'></sub></form><legend id='58x2e'></legend><bdo id='58x2e'><pre id='58x2e'><center id='58x2e'></center></pre></bdo></b><th id='58x2e'></th></span></q></dt></tr></i><div id='58x2e'><tfoot id='58x2e'></tfoot><dl id='58x2e'><fieldset id='58x2e'></fieldset></dl></div>
      <legend id='58x2e'><style id='58x2e'><dir id='58x2e'><q id='58x2e'></q></dir></style></legend>

      <small id='58x2e'></small><noframes id='58x2e'>

          <bdo id='58x2e'></bdo><ul id='58x2e'></ul>
      1. C# Google Drive APIv3 上传文件

        时间:2023-08-28

        • <tfoot id='441OW'></tfoot>
          <legend id='441OW'><style id='441OW'><dir id='441OW'><q id='441OW'></q></dir></style></legend>

            <bdo id='441OW'></bdo><ul id='441OW'></ul>
              <tbody id='441OW'></tbody>
          • <i id='441OW'><tr id='441OW'><dt id='441OW'><q id='441OW'><span id='441OW'><b id='441OW'><form id='441OW'><ins id='441OW'></ins><ul id='441OW'></ul><sub id='441OW'></sub></form><legend id='441OW'></legend><bdo id='441OW'><pre id='441OW'><center id='441OW'></center></pre></bdo></b><th id='441OW'></th></span></q></dt></tr></i><div id='441OW'><tfoot id='441OW'></tfoot><dl id='441OW'><fieldset id='441OW'></fieldset></dl></div>

                <small id='441OW'></small><noframes id='441OW'>

                  本文介绍了C# Google Drive APIv3 上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                  问题描述

                  我正在制作一个链接到 Google Drive 帐户的简单应用程序,然后可以将文件上传到任何目录并使用(直接)下载链接进行响应.我已经获得了我的 User Credentials 和 DriveService 对象,但我似乎找不到任何好的示例或文档.在 APIv3 上.

                  I'm making a simple Application that Links to a Google Drive Account and then can Upload Files to any Directory and respond with a (direct) download Link. I already got my User Credentials and DriveService objects, but I can't seem to find any good examples or Docs. on the APIv3.

                  由于我对 OAuth 不是很熟悉,因此我现在要求对如何上传包含 byte[] 内容的文件进行清晰而清晰的解释.

                  As I'm not very familiar with OAuth, I'm asking for a nice and clear explanation on how to Upload a File with byte[] content now.

                  我将应用程序链接到 Google Drive 帐户的代码:(不确定这是否完美)

                      UserCredential credential;
                  
                  
                          string dir = Directory.GetCurrentDirectory();
                          string path = Path.Combine(dir, "credentials.json");
                  
                          File.WriteAllBytes(path, Properties.Resources.GDJSON);
                  
                          using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
                              string credPath = Path.Combine(dir, "privatecredentials.json");
                  
                              credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                                  GoogleClientSecrets.Load(stream).Secrets,
                                  Scopes,
                                  "user",
                                  CancellationToken.None,
                                  new FileDataStore(credPath, true)).Result;
                          }
                  
                          // Create Drive API service.
                          _service = new DriveService(new BaseClientService.Initializer() {
                              HttpClientInitializer = credential,
                              ApplicationName = ApplicationName,
                          });
                  
                          File.Delete(path);
                  

                  到目前为止我的上传代码:(显然不起作用)

                          public void Upload(string name, byte[] content) {
                  
                          Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
                          body.Name = name;
                          body.Description = "My description";
                          body.MimeType = GetMimeType(name);
                          body.Parents = new List() { new ParentReference() { Id = _parent } };
                  
                  
                          System.IO.MemoryStream stream = new System.IO.MemoryStream(content);
                          try {
                              FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
                              request.Upload();
                              return request.ResponseBody;
                          } catch(Exception) { }
                      }
                  

                  谢谢!

                  推荐答案

                  启用 Drive API 后,注册项目并从 开发者控制台,您可以使用以下代码来获得用户的同意并获得经过身份验证的Drive Service

                  Once you have enabled your Drive API, registered your project and obtained your credentials from the Developer Consol, you can use the following code for recieving the user's consent and obtaining an authenticated Drive Service

                  string[] scopes = new string[] { DriveService.Scope.Drive,
                                               DriveService.Scope.DriveFile};
                  var clientId = "xxxxxx";      // From https://console.developers.google.com
                  var clientSecret = "xxxxxxx";          // From https://console.developers.google.com
                  // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                  var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
                                                                                                ClientSecret = clientSecret},
                                                                          scopes,
                                                                          Environment.UserName,
                                                                          CancellationToken.None,
                                                                          new FileDataStore("MyAppsToken")).Result; 
                  //Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent. 
                  
                  DriveService service = new DriveService(new BaseClientService.Initializer()
                  {
                     HttpClientInitializer = credential,
                     ApplicationName = "MyAppName",
                  });
                  service.HttpClient.Timeout = TimeSpan.FromMinutes(100); 
                  //Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.
                  

                  以下是上传到云端硬盘的工作代码.

                  Following is a working piece of code for uploading to Drive.

                      // _service: Valid, authenticated Drive service
                      // _uploadFile: Full path to the file to upload
                      // _parent: ID of the parent directory to which the file should be uploaded
                  
                  public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
                  {
                     if (System.IO.File.Exists(_uploadFile))
                     {
                         File body = new File();
                         body.Title = System.IO.Path.GetFileName(_uploadFile);
                         body.Description = _descrp;
                         body.MimeType = GetMimeType(_uploadFile);
                         body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
                  
                         byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
                         System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                         try
                         {
                             FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
                             request.Upload();
                             return request.ResponseBody;
                         }
                         catch(Exception e)
                         {
                             MessageBox.Show(e.Message,"Error Occured");
                         }
                     }
                     else
                     {
                         MessageBox.Show("The file does not exist.","404");
                     }
                  }
                  

                  这是确定 MimeType 的小函数:

                  Here's the little function for determining the MimeType:

                  private static string GetMimeType(string fileName)
                  {
                      string mimeType = "application/unknown";
                      string ext = System.IO.Path.GetExtension(fileName).ToLower();
                      Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
                      if (regKey != null && regKey.GetValue("Content Type") != null)
                          mimeType = regKey.GetValue("Content Type").ToString();
                      return mimeType;
                  }
                  

                  另外,您可以注册ProgressChanged事件并获取上传状态.

                  Additionally, you can register for the ProgressChanged event and get the upload status.

                   request.ProgressChanged += UploadProgessEvent;
                   request.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize; // Minimum ChunkSize allowed by Google is 256*1024 bytes. ie 256KB. 
                  

                   private void UploadProgessEvent(Google.Apis.Upload.IUploadProgress obj)
                   {
                       label1.Text = ((obj.ByteSent*100)/TotalSize).ToString() + "%";
                  
                      // do updation stuff
                   }
                  

                  上传就差不多了..

                  来源.

                  这篇关于C# Google Drive APIv3 上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:如何使用 .NET API 在 Google Drive 中创建文件夹? 下一篇:如何将 ISO8601 TimeSpan 转换为 C# TimeSpan?

                  相关文章

                  最新文章

                      <bdo id='oW4JG'></bdo><ul id='oW4JG'></ul>

                    <small id='oW4JG'></small><noframes id='oW4JG'>

                    <tfoot id='oW4JG'></tfoot>

                    <i id='oW4JG'><tr id='oW4JG'><dt id='oW4JG'><q id='oW4JG'><span id='oW4JG'><b id='oW4JG'><form id='oW4JG'><ins id='oW4JG'></ins><ul id='oW4JG'></ul><sub id='oW4JG'></sub></form><legend id='oW4JG'></legend><bdo id='oW4JG'><pre id='oW4JG'><center id='oW4JG'></center></pre></bdo></b><th id='oW4JG'></th></span></q></dt></tr></i><div id='oW4JG'><tfoot id='oW4JG'></tfoot><dl id='oW4JG'><fieldset id='oW4JG'></fieldset></dl></div>

                    <legend id='oW4JG'><style id='oW4JG'><dir id='oW4JG'><q id='oW4JG'></q></dir></style></legend>