2013-05-30 87 views
0

我決定在我的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小時? –

回答

2

我看到你正在讀取文件的所有內容到一個MemoryStream中,當上傳大文件時會明顯佔用大量的內存。你能避免它嗎?

你可以像下面這樣做嗎?

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

編輯

另外,如果您想上傳大文件,我想你也許應該考慮增加超時值,以防止被中止您的請求。

+0

我嘗試你的代碼,但它並沒有改變任何東西。我得到同樣的錯誤。 – muhammedkasva

+0

也許你可以查看我上面編輯過的帖子,看看它是否有效。 –

+0

你能解釋一下我們如何改變upload()方法的超時設置? –

0

嘗試更改請求的塊大小。

使用快速的互聯網連接,我們沒有問題。

但是移動到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/摸出你的上傳速度,並確定一個可靠的塊大小,而不會造成過多的開銷。