using System.IO; using GxPress.Service.Interface.Video; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.Caching.Distributed; namespace GxPress.Api.AppControllers { /// /// 访问 /// [Route("/api/app/video")] [ApiController] [Authorize] public class VideoController : ControllerBase { private readonly IWebHostEnvironment _environment; private readonly IDistributedCache _cache; private readonly IVideoService videoService; public VideoController(IWebHostEnvironment environment, IDistributedCache cache, IVideoService videoService) { _environment = environment; _cache = cache; this.videoService = videoService; } /// /// /// /// [HttpGet] [AllowAnonymous] public IActionResult GetVideo(int page) { try { var path = Common.Tools.StringUtils.GetWebRootPath(_environment.WebRootPath); var filepath = path + "/cache/20200428/music.mp4"; FileInfo fileInfo = new FileInfo(filepath); var key = $"music.mp4{page}"; var result = _cache.Get(key); if (result != null) { return File(result, "application/octet-stream", fileInfo.Name); } var blength = 1024 * 1024 * 5; byte[] bytsize = new byte[blength]; //获取文件名后缀 string extension = Path.GetExtension(filepath); // videoService.RedisVideo(filepath, bytsize, blength, "music.mp4"); //获取文件流 using (FileStream stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { while (true) { int r = stream.Read(bytsize, 0, blength); //如果读取到的字节数为0,说明已到达文件结尾,则退出while循 break; } stream.Close(); } //获取后缀名 var ext = fileInfo.Extension; new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype); return File(bytsize, contenttype ?? "application/octet-stream", fileInfo.Name); } catch (FileNotFoundException e) { throw new Common.Exceptions.BusinessException(e.Message); } catch (IOException e) { throw new Common.Exceptions.BusinessException(e.Message); } } } }