我正在尝试在Google云端硬盘上传大型文件,执行Resumable上传。
这是代码流
第1步:使用云服务在Google云端硬盘上创建文件并启动可恢复的上传会话 使用put请求
String fileID = _DriveService.Files.Insert(googleFileBody).Execute().Id;
//Initiating resumable upload session
String UploadUrl = null;
String _putUrl = "https://www.googleapis.com/upload/drive/v2/files/" + fileID + "?uploadType=resumable";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(_putUrl);
httpRequest.Headers["Authorization"] = "Bearer " + AccessToken;
httpRequest.Method = "PUT";
requestStream = httpRequest.GetRequestStream();
_webResponse = (HttpWebResponse)httpRequest.GetResponse();
if (_webResponse.StatusCode == HttpStatusCode.OK)
{
//Getting response OK
UploadUrl = _webResponse.Headers["Location"].ToString();
}
步骤2:将块上传到使用UploadUrl。字节数组是256kb的倍数,对此函数的调用在每个块的循环中
private void AppendFileData(byte[] chunk)
{
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(UploadUrl);
httpRequest.ContentLength = chunk.Length;
httpRequest.Headers["Content-Range"] = "bytes " + startOffset + "-" + endOffset+ "/" + sourceFileSize;
httpRequest.ContentType= MimeType;
httpRequest.Method = "PUT";
MemoryStream stream =new MemoryStream(chunk);
using (System.IO.Stream requestStream = httpRequest.GetRequestStream())
{
stream.CopyTo(requestStream);
requestStream.Flush();
requestStream.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)(httpRequest.GetResponse()); // Throws exception as
//System.Net.WebException: The remote server returned an error: (308) Resume Incomplete.
//at System.Net.HttpWebRequest.GetResponse()
// There is no data getting appended to file
// Still executing the append for remaining chunks
}
catch(System.Net.WebException ex)
{
}
}
对于我的最后一个不是256KB的倍数的块,我收到错误
System.Net.WebException:远程服务器返回错误:(400) 错误的请求。在System.Net.HttpWebRequest.GetResponse()
我在这段代码中做错了什么?请建议。 提前致谢
Mayuresh。
答案 0 :(得分:0)
尝试检查最后一个块是否传递了正确的大小而不是整个数组,如forum中所述。 Ali在该论坛中表示“一个潜在的问题是:如果你发送一个字节数组,该数组对于最后一个请求是半空的(即缓冲区的读取量小于块大小)。”以下是resumable upload的示例实现。希望这会有所帮助。