使用Google Drive V3 C#SDK恢复中断的上传 [英] Resuming interrupted upload using Google drive v3 C# sdk

查看:98
本文介绍了使用Google Drive V3 C#SDK恢复中断的上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Google Drive v3 C#SDK恢复中断的可恢复的上载. 我想要这样做的原因是在Restful Web API中创建可恢复的上载. RestAPI中有Google驱动器api实例,因此这会将块数据从客户端程序中继到Google驱动器. 如您所知,客户端程序无法一次将整个文件数据上传到Web API,因此我们需要恢复中断的可恢复上传.

I want to resume interrupted resumable upload using Google Drive v3 C# SDK. The reason why I want this is to create resumable upload in Restful Web API. There is google drive api instance in this RestAPI, so this is relaying chunk data from client program to google drive. As you know, client program cannot upload whole file data at one time to Web API, so we need to resume interrupted resumable upload.

所以我的计划在这里.

  • 首先,我们需要创建上传会话并接收会话URI.
  • 第二,每次根据返回的URI创建Upload实例并添加块数据.
  • 第三,重复第二步直到EOF.

为此,我编写了测试代码,但是它根本不起作用.

For this, I made test code, but it does not work at all.

var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,
            System.IO.FileAccess.Read);
var insert = service.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = title }, uploadStream, ContentType);

Uri uploadUri = insert.InitiateSessionAsync().Result;

int chunk_size = ResumableUpload.MinimumChunkSize;
while (uploadStream.Length != uploadStream.Position)
{
    byte[] temp = new byte[chunk_size];
    uploadStream.Read(temp, 0, temp.Length);
    MemoryStream stream = new MemoryStream(temp);

    ResumableUpload resume_uploader = ResumableUpload.CreateFromUploadUri(uploadUri, stream);

    resume_uploader.ChunkSize = chunk_size;
    IUploadProgress ss =  resume_uploader.Resume();

    Console.WriteLine("Uploaded " + ss.BytesSent.ToString());
}   

坦率地说,我希望收到308个恢复未完成的代码",但结果有所不同.

Frankly, I expected to receive 308 Resume Incomplete Code, but the result is different.

无效的请求.根据Content-Range标头,上传的最终大小为262144字节.这与先前的请求中指定的1193188字节的预期大小不匹配. "

"Invalid request. According to the Content-Range header, the final size of the upload is 262144 byte(s). This does not match the expected size of 1193188 byte(s), which was specified in an earlier request."

这意味着我需要创建代码,以使用Google Drive C#SDK恢复中断的可恢复的上载.

This means that I need to create code that resumes interrupted resumable upload using Google Drive C# SDK.

有人可以帮助我吗?

推荐答案

最后,我解决了问题.确切的代码如下.实际上,我在Google上找不到任何源代码,所以我感到非常难过.每个想要解决此问题的开发人员,请使用我的代码.希望你好好的. :)

Finally, I solved issue. Exact code is below. Actually, I could not find any source code on Google, so I was so sad. Every developer who wants to solve this issue, use my code please. Hope you are fine. :)

    public static async Task<Google.Apis.Drive.v3.Data.File> UploadSync(DriveService driveService, string filepath)
    {
        string destfilename = Path.GetFileName(filepath);

        List<string> parents = new List<string>();

        parents.Add("root");
        // Prepare the JSON metadata
        string json = "{\"name\":\"" + destfilename + "\"";
        if (parents.Count > 0)
        {
            json += ", \"parents\": [";
            foreach (string parent in parents)
            {
                json += "\"" + parent + "\", ";
            }
            json = json.Remove(json.Length - 2) + "]";
        }
        json += "}";
        Debug.WriteLine(json);

        Google.Apis.Drive.v3.Data.File uploadedFile = null;
        try
        {
            System.IO.FileInfo info = new System.IO.FileInfo(filepath);

            ulong fileSize = (ulong)info.Length;

            var uploadStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            var insert = driveService.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = destfilename, Parents = new List<string> { "root" } }, uploadStream, "application/octet-stream");

            Uri uploadUri = insert.InitiateSessionAsync().Result;

            int chunk_size = ResumableUpload.MinimumChunkSize;
            int bytesSent = 0;
            while (uploadStream.Length != uploadStream.Position)
            {
                byte[] temp = new byte[chunk_size];
                int cnt = uploadStream.Read(temp, 0, temp.Length);
                if (cnt == 0)
                    break;

                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uploadUri);

                httpRequest.Method = "PUT";
                httpRequest.Headers["Authorization"] = "Bearer " + ((UserCredential)driveService.HttpClientInitializer).Token.AccessToken;
                httpRequest.ContentLength = (long)cnt;
                httpRequest.Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", bytesSent, bytesSent + cnt - 1, fileSize);

                using (System.IO.Stream requestStream = httpRequest.GetRequestStreamAsync().Result)
                {
                    requestStream.Write(temp, 0, cnt);
                }

                HttpWebResponse httpResponse;
                try
                {
                    httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    httpResponse = (HttpWebResponse)ex.Response;
                }

                if (httpResponse.StatusCode == HttpStatusCode.OK)
                { }
                else if ((int)httpResponse.StatusCode != 308)
                    break;

                bytesSent += cnt;

                Console.WriteLine("Uploaded " + bytesSent.ToString());
            }

            if (bytesSent != uploadStream.Length)
            {
                return null;
            }

            // Try to retrieve the file from Google
            FilesResource.ListRequest request = driveService.Files.List();
            if (parents.Count > 0)
                request.Q += "'" + parents[0] + "' in parents and ";
            request.Q += "name = '" + destfilename + "'";
            FileList result = request.Execute();
            if (result.Files.Count > 0)
                uploadedFile = result.Files[0];
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }

        return uploadedFile;
    }

这篇关于使用Google Drive V3 C#SDK恢复中断的上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆