Google Drive Api .Net上传错误

问题描述:

我决定在我的WPF项目中使用Google驱动器api。我搜索了很多文档和样本。我学会了并成功了.Everyhing运行良好。我使用这个函数来插入/上传。Google Drive Api .Net上传错误

public static Google.Apis.Drive.v2.Data.File InsertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) 
     { 
      Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File(); 
      body.Title = title; 
      body.Description = description; 
      body.MimeType = mimeType; 
      if (!String.IsNullOrEmpty(parentId)) 
      { 
       body.Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } }; 
      } 
      byte[] byteArray = System.IO.File.ReadAllBytes(filename); 
      MemoryStream stream = new MemoryStream(byteArray); 
      try 
      { 
       FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); 
       request.Upload(); 
       Google.Apis.Drive.v2.Data.File file = request.ResponseBody; 
       return file; 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("An error occurred: " + e.Message); 
      } 
     } 

当我想上传一个小文件到谷歌驱动器,它的工作原理。但我选择上传大型文件,它提供了一个错误,并fails.I得到这个错误

System.Net.WebException was caught HResult=-2146233079 Message=The request was aborted: The request was canceled.Source=System StackTrace: 
    at System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state) 
    at System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size) 
    at Google.Apis.Upload.ResumableUpload`1.SendChunk(Stream stream, Uri uri, Int64 position) 
    at Google.Apis.Upload.ResumableUpload`1.Upload() 
    at Google.Apis.Util.Utilities.InsertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) in .. 

我寻找这个错误,并满足同样的问题,但我不明白的地方,我wrong.Can任何人的帮助我或清楚地修复我的代码。 谢谢:)

+0

该文件有多大,上传需要多长时间? –

+0

我尝试16mb,30mb大小的文件,它给出了一个错误。如果我想上传小文件没有关系。 – muhammedkasva

+0

上传时间是否超过1小时? –

我看到你正在读取文件的所有内容到一个MemoryStream中,当上传大文件时会明显占用大量的内存。你能避免它吗?

你可以像下面这样做吗?

FilesResource.InsertMediaUpload request = service.Files.Insert(body, File.OpenRead(filename), mimeType);

编辑

另外,如果您想上传大文件,我想你也许应该考虑增加超时值,以防止被中止您的请求。

+0

我尝试你的代码,但它并没有改变任何东西。我得到同样的错误。 – muhammedkasva

+0

也许你可以查看我上面编辑过的帖子,看看它是否有效。 –

+0

你能解释一下我们如何改变upload()方法的超时设置? –

尝试更改请求的块大小。

使用快速的互联网连接,我们没有问题。

但是移动到ADSL连接,我们注意到它会超过任何大于5MB的文件。

我们建立我们的对

request.ChunkSize = 256 * 1024; 

默认情况下,谷歌使用10,485,760字节,这是10MB。因此,如果您在超时期限内无法上传10MB,则会出现错误。

为了帮助您解决问题,请订阅ProgressChanged事件和输出每次它被击中

request.ProgressChanged += request_ProgressChanged; 

.... 

static void request_ProgressChanged(Google.Apis.Upload.IUploadProgress obj) 
{ 
    var output = String.Format("Status: {0} Bytes: {1} Exception: {2}", obj.Status, obj.BytesSent, obj.Exception); 
    System.Diagnostics.Debug.WriteLine(output); 
} 

我个人的意见是得到答复每10-20秒。 60秒+太长。

您也可以使用类似http://www.speedtest.net/摸出你的上传速度,并确定一个可靠的块大小,而不会造成过多的开销。