这个想法很简单,我正在创建一个服务,用户可以在其中放置托管在另一个网站上的文件的直接链接,我的程序将打开到该远程服务器的流并开始以字节为单位读取文件,然后返回每个读取的文件字节给用户。
到目前为止,我设法让它工作,这是我的代码
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();
}
}
}
当我转到我的页面时,它下载得很好,但问题是如果我停止下载,它就不会再次恢复。
我搜索了该问题,发现必须在连接中定义一个标头“Accept-Ranges”才能支持恢复。
所以我添加了该标头但不起作用。
处理范围请求 http://www.w3.org/Protocols/rfc2616/rfc2616.html比这稍微复杂一点。一般来说,你需要处理Range
and If-Range
请求中的标头并正确提供服务第206章 部分内容回应Content-Range
, Date
and ETag
or Content-Location
标头。
文章ASP.NET MVC 中的范围请求 – RangeFileResult https://www.tpeczek.com/2011/10/range-requests-in-aspnet-mvc.html详细描述了如何创建 ASP.NET MVCActionResult
with 范围请求支持。
在您的情况下,您还必须检查另一侧(您使用的一侧)是否fileReq
) 支持范围请求。如果是,那么您可以只请求所需的部分(最好将其缓存在本地某个地方),但如果不是,您需要获取整个文件并寻找正确的位置(在这种情况下,您肯定希望有一个本地缓存方案)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)