好吧,我不知道为什么这不起作用。同样的代码只适用于上传元数据,然后适用于多部分上传。我无法将可恢复上传到工作中。
Uploading Files说步骤1应该返回一个200 ok,并带有upload_id,但是下面的行没有返回任何内容。内容长度为0,没有错误响应,什么都没有。
string responseFromServer = reader.ReadToEnd();
我的代码:
FileInfo info = new FileInfo(pFilename);
String MimeType = GetMimeType(pFilename).ToString();
string footer = "rn";
//Createing the MetaData to send
List<string> _postData = new List<string>();
_postData.Add("{");
_postData.Add(""title": "" + info.Name + """);
_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 url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable";
int headerLenght = MetaDataByteArray.Length +footer.Length;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", string.Format("Bearer {0}", myAutentication.accessToken));
request.ContentLength = headerLenght;
request.ContentType = "application/json; charset=UTF-8";
request.Headers.Add("X-Upload-Content-Type", MimeType);
request.Headers.Add("X-Upload-Content-Length", FileByteArray.Length.ToString());
Stream dataStream = request.GetRequestStream();
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); // done writeing add return just
dataStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Display the status. IT returns OK
// 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. ResponseFromServer returns "" nothing.
//Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
return "Exception uploading file: uploading file." + ex.Message;
//return Error.CreateJsonError("HttpWeb.Post", "1", "Error: " + ex.Message);
}
我终于弄明白了。Upload id在响应标头中返回。
WebResponse response = request.GetResponse();
string Location = response.Headers["Location"];