2014-01-16 74 views
1

我可以從我的網站上傳文件到谷歌驅動器,但是我的問題是它會在上傳後顯示文件爲無標題。Google Drive api上傳文件名爲「無標題」

如何添加或發佈標題到上傳文件。

感謝,

我的代碼:

public string UploadFile(string accessToken, byte[] file_data, string mime_type) 
    { 
     try 
     { 
      string result = ""; 
      byte[] buffer = file_data; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=media"); 

      request.Method = "POST"; 

      request.ContentType = mime_type; 
      request.ContentLength = buffer.Length; 
      request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken); 

      var stream = request.GetRequestStream(); 
      stream.Write(file_data, 0, file_data.Length); 
      stream.Close(); 

      HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();//Get error here 
      if(webResponse.StatusCode == HttpStatusCode.OK) 
      { 
       Stream responseStream = webResponse.GetResponseStream(); 
       StreamReader responseStreamReader = new StreamReader(responseStream); 
       result = responseStreamReader.ReadToEnd();//parse token from result 

       var jLinq = JObject.Parse(result); 

       JObject jObject = JObject.Parse(jLinq.ToString()); 

       webResponse.Close(); 

       return jObject["alternateLink"].ToString(); 
      } 

      return string.Empty; 


     } 
     catch 
     { 
      return string.Empty; 
     } 
    } 

回答

2

使用google.apis的DLLs出來做它不是那麼容易。在發送文件的其餘部分之前,您需要發送元數據。對於那些需要使用uploadType =多

https://developers.google.com/drive/manage-uploads#multipart

這應該讓你開始對不起它的代碼牆。我還沒有時間爲此創建教程。

FileInfo info = new FileInfo(pFilename); 
//Createing the MetaData to send 
List<string> _postData = new List<string>(); 
_postData.Add("{"); 
_postData.Add("\"title\": \"" + info.Name + "\","); 
_postData.Add("\"description\": \"Uploaded with SendToGoogleDrive\","); 
_postData.Add("\"parents\": [{\"id\":\"" + pFolder + "\"}],"); 
_postData.Add("\"mimeType\": \"" + GetMimeType(pFilename).ToString() + "\""); 
_postData.Add("}"); 
string postData = string.Join(" ", _postData.ToArray()); 
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData); 

// creating the Data For the file 
byte[] FileByteArray = System.IO.File.ReadAllBytes(pFilename); 

string boundry = "foo_bar_baz"; 
string url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + myAutentication.accessToken; 

WebRequest request = WebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "multipart/related; boundary=\"" + boundry + "\""; 

// Wrighting Meta Data 
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n", 
       boundry, 
       "application/json; charset=UTF-8"); 
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n", 
       boundry, 
       GetMimeType(pFilename).ToString()); 

string footer = "\r\n--" + boundry + "--\r\n"; 

int headerLenght = headerJson.Length + headerFile.Length + footer.Length; 
request.ContentLength = MetaDataByteArray.Length + FileByteArray.Length + headerLenght; 
Stream dataStream = request.GetRequestStream(); 
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType 
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length);           // write the MetaData 


dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType 
     dataStream.Write(FileByteArray, 0, FileByteArray.Length);         // write the file 

     // Add the end of the request. Start with a newline 

     dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); 
     dataStream.Close(); 

     try 
     { 
      WebResponse response = request.GetResponse(); 
      // Get the stream containing content returned by the server. 
      dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 
      // Read the content. 
      string responseFromServer = reader.ReadToEnd(); 
      // Display the content. 
      //Console.WriteLine(responseFromServer); 
      // Clean up the streams. 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 
} 
     catch (Exception ex) 
     { 
      return "Exception uploading file: uploading file." + ex.Message; 

     } 

如果你需要超出評論的任何explinations讓我知道。我努力讓這個工作一個月。它幾乎和可恢復的上傳一樣糟糕。

+1

你好,非常感謝它爲我工作。我搜索了2天以上。再次感謝。 – chandran

3

我用RestSharp上傳文件到谷歌驅動器。

public static void UploadFile(string accessToken, string parentId) 
    { 
     var client = new RestClient { BaseUrl = new Uri("https://www.googleapis.com/") }; 

     var request = new RestRequest(string.Format("/upload/drive/v2/files?uploadType=multipart&access_token={0}", accessToken), Method.POST); 

     var bytes = File.ReadAllBytes(@"D:\mypdf.pdf"); 

     var content = new { title = "mypdf.pdf", description = "mypdf.pdf", parents = new[] { new { id = parentId } }, mimeType = "application/pdf" }; 

     var data = JsonConvert.SerializeObject(content); 

     request.AddFile("content", Encoding.UTF8.GetBytes(data), "content", "application/json; charset=utf-8"); 

     request.AddFile("mypdf.pdf", bytes, "mypdf.pdf", "application/pdf"); 

     var response = client.Execute(request); 

     if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Unable to upload file to google drive"); 
    } 
0

我正在尋找給定問題的解決方案,以前我把uploadType =可恢復導致給定的問題,當我用uploadType =多問題得到解決......

相關問題