前情提要
https://www.cnblogs.com/puzhiwei/p/15265005.html
在解決.Net5 如何修改Content-Disposition實現在線預覽的功能后,我又遇到了新的問題,那就是在預覽視頻文件時無法拖動進度條。我嘗試了多種解決方案都沒有解決這個問題,首先我先對這個問題進行了一番搜索,但是並沒有發現什么解決方法。但是在Google時,我發現這個問題是一個分段下載的問題。於是我就搜索了.Net5分段下載。
果然,我找到了一些.Net5分段下載的文章。
像這個 https://www.cnblogs.com/xxred/p/7931757.html
以及這個 https://www.cnblogs.com/tianma3798/p/13445111.html
但是都不太好用。
於是我就開始了繼續搜索。
wwwroot下文件的加載
我嘗試將視頻文件放到.Net默認的靜態文件加載目錄wwwroot下,然后直接訪問wwwroot里的視頻文件,我發現這個是可以拖動的,並且響應頭與請求頭中多出了Content-Range這個信息。
MDN 上說 在HTTP協議中,響應首部 Content-Range 顯示的是一個數據片段在整個文件中的位置。
那么問題就很清楚了,就是如何實現在視頻傳輸時添加Content-Range的問題,於是我又開始了搜索 .net5 file Content-Range,別說,還真找到了一些方案
這個
https://www.codeproject.com/Articles/820146/HTTP-Partial-Content-In-ASP-NET-Web-API-Video
還有這個
過於復雜且不知道好不好用,然后我就接着搜。
Github 的結果
於是我就在Github上找到了這個https://github.com/aspnet/Mvc/pull/6895
看了看好像就是說 return File()
時如何實現分段傳輸文件的方法的。
看了看使用方法好像還是不太會用,不過不重要,我已經知道該搜索什么了。
enableRangeProcessing
接着搜 enableRangeProcessing 我就發現了這篇文章 https://www.cnblogs.com/tianma3798/p/13445147.html ,其中提到了enableRangeProcessing 直接設置 true 即可啟用對按范圍返回文件流的支持,至此問題解決。
最新代碼
[Route("load")]
[HttpGet]
public async Task<IActionResult> DownloadFile(string path, string type)
{
if (string.IsNullOrEmpty(path))
{
return Content("404 for not found!");
}
try
{
// 獲取文件的ContentType
string fileExt = Path.GetExtension(path);
var provider = new FileExtensionContentTypeProvider();
var memi = provider.Mappings[fileExt];
if (type == "inline")
{
Response.Headers.Add("Content-Disposition", $"inline; filename={System.Net.WebUtility.UrlEncode(Path.GetFileName(filePath))}");
return PhysicalFile(filePath, memi, true);
//return File(memoryStream, memi, true);
}
return PhysicalFile(filePath, memi, Path.GetFileName(filePath), true);
}
catch (DirectoryNotFoundException e)
{
_logger.LogError($"文件:{path},沒有找到!\n{e.Message}");
return Content("404 for not found!");
}
}
總結
通過這次問題的解決,告訴我一個道理,要是一個問題一開始搜索沒有什么解決方案,說不定看一下源碼才是問題最好的解決方案。就能看到enableRangeProcessing
這個參數,快速的去解決這個問題。
//
// 摘要:
// Returns the file specified by physicalPath (Microsoft.AspNetCore.Http.StatusCodes.Status200OK)
// with the specified contentType as the Content-Type. This supports range requests
// (Microsoft.AspNetCore.Http.StatusCodes.Status206PartialContent or Microsoft.AspNetCore.Http.StatusCodes.Status416RangeNotSatisfiable
// if the range is not satisfiable).
//
// 參數:
// physicalPath:
// The path to the file. The path must be an absolute path.
//
// contentType:
// The Content-Type of the file.
//
// enableRangeProcessing:
// Set to true to enable range requests processing.
//
// 返回結果:
// The created Microsoft.AspNetCore.Mvc.PhysicalFileResult for the response.
版權信息
本文首發於 https://www.buguagaoshu.com/archives/aspnet5傳輸視頻文件無法快進