【问题标题】:Ensure file upload on Google Drive C#确保文件上传到 Google Drive C#
【发布时间】:2017-07-19 17:08:35
【问题描述】:

我正在开发将文件上传到 Google Drive 的 C# Windows 应用程序。我需要确定已上传到 Google Drive 上的文件,以防出现任何故障。

我想避免出现这样的情况,即文件开始上传,但网络中断,只有部分文件被上传。

我如何比较那些传输到 Google 云端硬盘的文件没有任何问题。

下面是我用来将文件上传到 Google Drive 的代码。

public static File uploadFile(DriveService _service, string _uploadFile, string _parent)
{
     if (System.IO.File.Exists(_uploadFile))
     {
          File body = new File();
          body.Title = System.IO.Path.GetFileName(_uploadFile);
          body.Description = "File uploaded by Diamto Drive Sample";
          body.MimeType = GetMimeType(_uploadFile);
          body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

          // File's content.
          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();

              Google.Apis.Drive.v2.Data.File file = request.ResponseBody;
              Google.Apis.Drive.v2.Data.Permission newPermission = new Google.Apis.Drive.v2.Data.Permission();
              newPermission.Value = "123@gmail.com";
              newPermission.Type = "anyone";
              newPermission.Role = "writer";
              _service.Permissions.Insert(newPermission, file.Id).Execute();

              return request.ResponseBody;
         }
         catch (Exception e)
         {
             Console.WriteLine("An error occurred: " + e.Message);
             return null;
         }
     }
     else
     {
         Console.WriteLine("File does not exist: " + _uploadFile);
         return null;
     }
 }

【问题讨论】:

  • 如果失败,它将返回 HTTP 409,否则客户端会出现异常。您可以使用预生成的 ID 重试上传,请参阅link 了解更多详细信息。
  • @Berkays 感谢您的提示。但是现在当文件成功上传时,我也将响应正文设为 NULL。所以我永远不会知道id。这就是为什么我想手动检查。

标签: c# google-drive-api


【解决方案1】:

您可以注册ProgressChanged 事件并检查UploadStatus 属性以确认上传成功。

request.ProgressChanged += UploadProgessEvent;

private void UploadProgessEvent(Google.Apis.Upload.IUploadProgress obj)
{
    if (obj.Status == Google.Apis.Upload.UploadStatus.Completed)
    {
        //Succesfully Uploaded
    }
}

IUploadProgress 中还有一个BytesSent 属性,您可以将其与原始文件大小进行比较以检查上传完成情况。


但是,正如 KENdi 引用的答案中提到的,来自insert Documentation

如果成功,此方法会在响应正文中返回一个 Files 资源。

如果上传因任何原因失败,将引发异常,catch 块必须处理它。

【讨论】:

  • 我认为进度改变事件会有所帮助。我将尝试实现这一点。
【解决方案2】:

尝试检查这个相关的SO问题是否可以帮助您确定文件上传是否成功。

现在,关于你正在进行的文件上传,如果你想避免在互联网连接断开时停止上传,那么尝试使用Resumable upload,该协议允许你恢复上传操作通信故障后中断数据流。

SO question 将向您展示如何在 C# 中使用可恢复上传。

希望这些信息对您有所帮助。

【讨论】:

猜你喜欢
  • 2020-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多