videoController.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.IO;
  2. using GxPress.Service.Interface.Video;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Hosting;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.StaticFiles;
  7. using Microsoft.Extensions.Caching.Distributed;
  8. namespace GxPress.Api.AppControllers
  9. {
  10. /// <summary>
  11. /// 访问
  12. /// </summary>
  13. [Route("/api/app/video")]
  14. [ApiController]
  15. [Authorize]
  16. public class VideoController : ControllerBase
  17. {
  18. private readonly IWebHostEnvironment _environment;
  19. private readonly IDistributedCache _cache;
  20. private readonly IVideoService videoService;
  21. public VideoController(IWebHostEnvironment environment, IDistributedCache cache, IVideoService videoService)
  22. {
  23. _environment = environment;
  24. _cache = cache;
  25. this.videoService = videoService;
  26. }
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <returns></returns>
  31. [HttpGet]
  32. [AllowAnonymous]
  33. public IActionResult GetVideo(int page)
  34. {
  35. try
  36. {
  37. var path = Common.Tools.StringUtils.GetWebRootPath(_environment.WebRootPath);
  38. var filepath = path + "/cache/20200428/1588144602647614.mp4";
  39. FileInfo fileInfo = new FileInfo(filepath);
  40. var key = $"15881446026476141.mp4{page}";
  41. var result = _cache.Get(key);
  42. if (result != null)
  43. return File(result, "application/octet-stream", fileInfo.Name);
  44. var blength = 1024 * 1024 * 1;
  45. byte[] bytsize = new byte[blength];
  46. //获取文件名后缀
  47. string extension = Path.GetExtension(filepath);
  48. //
  49. videoService.RedisVideo(filepath, bytsize, blength, "15881446026476141.mp4");
  50. //获取文件流
  51. using (FileStream stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  52. {
  53. while (true)
  54. {
  55. int r = stream.Read(bytsize, 0, blength);
  56. //如果读取到的字节数为0,说明已到达文件结尾,则退出while循
  57. break;
  58. }
  59. stream.Close();
  60. }
  61. //获取后缀名
  62. var ext = fileInfo.Extension;
  63. new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
  64. return File(bytsize, contenttype??"application/octet-stream", fileInfo.Name);
  65. }
  66. catch (FileNotFoundException e)
  67. {
  68. throw new Common.Exceptions.BusinessException(e.Message);
  69. }
  70. catch (IOException e)
  71. {
  72. throw new Common.Exceptions.BusinessException(e.Message);
  73. }
  74. }
  75. }
  76. }