C#服务器下载文件并同时传输给用户下载失败 [Google Drive]

问题描述

我正在使用 ASP.NET Core 编写程序。

程序将从 Google Drive 下载文件,而不将其存储在内存或磁盘中并将其传输给用户

Google Drive 官方库中的下载功能在下载完成后才会继续。为此,我向 API 发送了一个普通的 GET 请求,并将文件作为流读取并返回给用户

但到一定大小后,在IDM或浏览器等程序中下载会导致错误

总之,我想做一个程序,以服务器为桥接器,不应该被中断。

    [HttpGet]
    [disableRequestSizeLimit]
    public async Task<FileStreamResult> Download([FromQuery(Name = "file")] string fileid)
    {
        if (!string.IsNullOrEmpty(fileid))
        {
         
           
          
            var decoded = Base64.Base64Decode(fileid);
            var file = DriveAPI.service.Files.Get(decoded);
            file.SupportsAllDrives = true;
            file.SupportsTeamDrives = true;
           
            var fileinf = file.Execute();
            var filesize = fileinf.FileSize;

            var cli = new HttpClient(DriveAPI.service.HttpClient.MessageHandler);
            //var req = await cli.SendAsync(file.CreateRequest());

            var req = await cli.GetAsync($"https://www.googleapis.com/drive/v2/files/{decoded}?alt=media",HttpCompletionoption.ResponseHeadersRead);

            //var req = await DriveAPI.service.HttpClient.GetAsync($"https://www.googleapis.com/drive/v2/files/{decoded}?alt=media",HttpCompletionoption.ResponseHeadersRead);
            var contenttype = req.Content.Headers.ContentType.MediaType;

            if (contenttype == "application/json")
            {
                var message = JObject.Parse(req.Content.ReadAsstringAsync().Result).SelectToken("error.message");

                if (message.ToString() == "The download quota for this file has been exceeded")
                {
                    throw new Exception("Google Drive Günlük İndirme Kotası Aşıldı. Lütfen 24-48 Saat Sonra Tekrar Deneyin.");
                }
                else
                {
                    throw new Exception(message.ToString());
                }
            }
            else 
            {
               
                return File(req.Content.ReadAsstream(),contenttype,fileinf.OriginalFilename,false);
            }
        }
        else
        {
            return null;
        }
    }

下载时一些错误被写入日志文件

从传输流中收到意外的 EOF 或 0 字节。

无法从传输连接读取数据。

如果用户使用的是 IDM,则错误为:

服务器在重启命令时发送错误答案

如果用户正在从浏览器下载,则错误为:

网络错误

当大约下载大小为 900Mb 时,我开始使用 8 mbps 互联网下载 1.5Gb 文件,IDM 因上述错误而停止下载。

除了在 ASP.NET Core 中返回 FileStreamResult 之外,我不知道如何下载并发文件

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)