恢复下载(Resuming downloading)

2019-08-17 23:03发布

这个想法很简单,我创建一个服务,其中用户可以把正在被其他网站上承载的文件的直接链接,我的程序会打开一个流到远程服务器,并开始读取字节的文件,然后返回各自readed字节给用户。

到目前为止,我设法让该工作,这里是我的代码

    public void Index()
    {
        //Create a stream for the file
        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000; //10000

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create("http://SOME-OTHER-SERVER.com/File.rar");


            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();


            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.AddHeader("Content-Disposition", "attachment; filename=\"" + "fle.rar" + "\"");
            resp.AddHeader("Content-Length", (fileResp.ContentLength).ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (resp.IsClientConnected)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.OutputStream.Write(buffer, 0, length);

                    // Flush the data
                    resp.Flush();

                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }
    }

当我去到我的网页它下载完美,但问题是,如果我停止下载,不会再恢复。

我搜索了这个问题想通了,有一个标题“接受范围”,但必须在以支持恢复连接来定义。

所以我说这头,但没有奏效。

Answer 1:

处理范围请求比这更复杂一点。 一般来说,你需要处理的RangeIf-Range的请求头和服务与适当的206项部分内容的响应Content-RangeDateETagContent-Location标头。

文章在ASP.NET MVC范围请求- RangeFileResult详细描述了如何创建ASP.NET MVC ActionResult范围请求支持。

在你的情况,你也必须检查另一侧(您使用一个fileReq支持范围请求 )。 如果是的话比你可以要求只需要的部分(最好缓存某处地方),但如果不是你需要得到整个文件,并寻求合适的位置(在这种情况下,你defintely想有一个本地缓存的情况)。



文章来源: Resuming downloading