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(); 
相关问题