0

更新1文件上傳到谷歌驅動器在Windows Store應用

我想我使用了不正確的URL,this doc說,使用「https://www.googleapis.com/drive/v2/files」 & 說,使用「https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart」。雖然我得到了同樣的400個不好的要求。

我可以在後臺上傳類中使用Google Drive上傳REST API嗎?


我下面從谷歌驅動器上傳文件,但我得到400 - 錯誤的請求。我的代碼有什麼問題?

public static async Task UploadFileAsync(Token AuthToken, StorageFile file, DriveFile objFolder) 
{ 
    try 
    { 
     if (!httpClient.DefaultRequestHeaders.Contains("Authorization")) 
     { 
      httpClient.DefaultRequestHeaders.Add("Authorization", AuthToken.TokenType + " " + AuthToken.AccessToken); 
     } 

     var JsonMessage = JsonConvert.SerializeObject(objFolder); 
     /*JsonMessage = {"title":"c4611_sample_explain.pdf","mimeType":"application/pdf","parents":[{"id":"root","kind":"drive#fileLink"}]}*/ 
     var JsonReqMsg = new StringContent(JsonMessage, Encoding.UTF8, "application/json"); 

     var fileBytes = await file.ToBytesAsync(); 

     var form = new MultipartFormDataContent(); 
     form.Add(new ByteArrayContent(fileBytes)); 
     form.Add(JsonReqMsg); 

     form.Headers.ContentType = new MediaTypeHeaderValue("multipart/related"); 

     var UploadReq = await httpClient.PostAsync(new Uri("https://www.googleapis.com/drive/v2/files?uploadType=multipart"), form); 

     if (UploadReq.IsSuccessStatusCode) 
     { 
      var UploadRes = await UploadReq.Content.ReadAsStringAsync(); 
     } 
     else 
     { 

     } 
    } 
    catch (Exception ex) 
    { 

    } 
} 
+0

只是一個猜測 - 很多次,「400不好的請求「表示認證有問題(無效的用戶名/密碼/其他)。這裏的一個例子:[AccessToken for Windows推送通知返回錯誤的請求400](http://stackoverflow.com/questions/15517822/accesstoken-for-windows-push-notifications-returns-bad-request-400)。 –

+0

我的猜測是,問題coudl是相關的,因爲您正在使用'MultipartFormDataContent'而不是'MultipartContent',而'Content-Type:multipart/related'可能會被覆蓋。在這種情況下,提琴手痕跡會有所幫助。 – kiewic

回答

0

您必須使用https://www.googleapis.com/upload/drive/v2/files

我這裏有一個工作示例(對不起,JSON字符串是硬編碼):

// Multipart file upload 
HttpClient client = new HttpClient(); 
string uriString = "https://www.googleapis.com/upload/drive/v2/files?key=<your-key>&access_token=<access-token>&uploadType=multipart"; 
Uri uri = new Uri(uriString); 

HttpContent metadataPart = new StringContent(
    "{ \"title\" : \"My File\"}", 
    Encoding.UTF8, 
    "application/json"); 

HttpContent mediaPart = new StringContent(
    "The naughty bunny ate all the cookies.", 
    Encoding.UTF8, 
    "text/plain"); 

MultipartContent multipartContent = new MultipartContent(); 
multipartContent.Add(metadataPart); 
multipartContent.Add(mediaPart); 

HttpResponseMessage response = await client.PostAsync(uri, multipartContent); 
string responseString = await response.Content.ReadAsStringAsync(); 
相關問題