Background:對於音視頻在線播放,一些小應用是靠nginx處理訪問視頻、音頻文件的請求,對外應用的通常會託管至各類雲上使用相關的服務。前者存在巨大的安全隱患,後者會有必定的成本。有的時候仍是須要本身造個輪子。html
step 1:先實現文件下載前端
[HttpGet] public IActionResult Get() { var filePath = @"E:\test.wav"; var name = @"tes1t.wav"; FileStream fs = new FileStream(filePath, FileMode.Open); return File(fs, "application/octet-stream", name); }
前面的audio標籤是能夠播放和正常下載的,可是並不能實現進度控件的調整nginx
step2:請求的區別安全
Nginx的處理是能夠實現播放進度調整的。在前端請求相同的狀況下,二者用nginx代理和剛纔的下載的主要區別以下:app
能夠看出Content-Range對應的正是請求頭中的Rangeide
關於這幾個頭部信息可參考這篇文章:https://blog.csdn.net/thewindkee/article/details/80189434spa
這3個標籤同時也是文件實現斷點續傳的關鍵。.net
step3:斷點續傳3d
這樣進度的調整就轉化爲了斷點續傳功能。代理
.net可參考:http://www.javashuo.com/article/p-wjbuzpjd-dm.html
1 public FileStreamResult Index(string auth,string filename) 2 { 3 if (auth != null && auth.Length >7) 4 { 5 // 處理權限問題 6 } 7 else 8 { 9 return null; 10 } 11 12 int size, end, length = 0; 13 int start; 14 15 MemoryStream Mstream; 16 using (FileStream reader = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) 17 { 18 byte[] bytes = new byte[reader.Length]; 19 //var strd = new StreamReader(reader); 20 21 size = bytes.Length; 22 start = 0; 23 end = size - 1; 24 length = size; 25 Response.Headers["Accept-Ranges"] = "0-" + size; 26 if (!String.IsNullOrEmpty(Request.Headers["Range"])) 27 { 28 int anotherStart = start; 29 int anotherEnd = end; 30 var headerRange = Request.Headers["Range"]; 31 string[] arr_split = headerRange.FirstOrDefault().Split(new char[] { Convert.ToChar("=") }); 32 Debug.WriteLine(arr_split); 33 string range = arr_split[1]; 34 if (range.IndexOf(",") > -1) 35 { 36 Response.Headers["Content-Range"] = "bytes " + start + "-" + end + "/" + size; 37 38 Response.StatusCode = 416; 39 40 } 41 if (range.StartsWith("-")) 42 { 43 // The n-number of the last bytes is requested 44 anotherStart = size - Convert.ToInt32(range.Substring(1)); 45 } 46 else 47 { 48 arr_split = range.Split(new char[] { Convert.ToChar("-") }); 49 anotherStart = Convert.ToInt32(arr_split[0]); 50 int temp = 0; 51 anotherEnd = (arr_split.Length > 1 && Int32.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt32(arr_split[1]) : size; 52 } 53 anotherEnd = (anotherEnd > end) ? end : anotherEnd; 54 if (anotherStart > anotherEnd || anotherStart > size - 1 || anotherEnd >= size) 55 { 56 Response.Headers["Content-Range"] = "bytes " + start + "-" + end + "/" + size; 57 Response.StatusCode = 416; 58 59 } 60 start = anotherStart; 61 end = anotherEnd; 62 length = end - start + 1; // Calculate new content length 63 reader.Read(bytes, start, length); 64 Response.StatusCode = 206; 65 } 66 else 67 { 68 reader.Read(bytes, 0, bytes.Length); 69 } 70 Mstream = new MemoryStream(bytes); 71 } 72 Response.Headers["Content-Range"] = "bytes " + start + "-" + end + "/" + size; 73 Response.Headers["Content-Length"] = length.ToString(); 74 Response.Headers.Add("Content-Disposition", "attachment; filename=download.wav"); 75 return new FileStreamResult(Mstream, "applicaton/octet-stream"); 76 }