簡體   English   中英

使用 c# ASP.NET MVC 獲取視頻播放

[英]Getting Video To play using c# ASP.NET MVC

我試圖讓人們將視頻保存在數據庫中,然后其他用戶可以在線觀看這些視頻。 我將文件保存在 wwwroot/videos/Username 中,同時將其他信息(視頻名稱、描述、url)保存在數據庫中。 得到了所有要保存的文件,但似乎無法播放視頻。 做了一些研究,發現由於安全原因,firefox 和 chrome 無法從您的磁盤播放視頻。 將 IFormFile 視頻文件正確保存到數據庫並收工是否更好? 或者有沒有辦法使這項工作?

上傳和保存視頻:

[HttpPost]
public async Task<IActionResult> UploadVideo(VideoViewModel video, IFormFile file)
{
    if (file.Length > 0)
    {
        try
        {
            string userName = (User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Name).Value);
            string pathString = Path.Combine(@"path", userName);
            if (!Directory.Exists(pathString))
            {
                Directory.CreateDirectory(pathString);
            }
            int fCount = Directory.GetFiles(pathString, "*", SearchOption.TopDirectoryOnly).Length + 1;
            var filePath = Path.Combine(pathString, file.FileName);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
                _videoLogic.SaveVideo(new Video(video.VideoId, video.Description, file.FileName, DateTime.Now, filePath, video.CategoryId));
            }
        }
        catch (Exception ex)
        {
            ViewBag.Message = "ERROR: " + ex.Message.ToString();
        }
    }
    else
    {
        ViewBag.Message = "You have not specified a file.";
    }
    return RedirectToAction("UploadVideo");
}

嘗試觀看視頻:

<h2>Overzicht Videos gebruiker</h2>

<!DOCTYPE html>
<html>
<head>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        @foreach(var item in Model)
        {
            <div class="col-sm-4 col-md-4 col-xs-12">
                <div class="modal-title" style="width:250px;">@item.Name</div>
                <hr/>
                <div class="video-frame">
                    <video style="width:250px; height:150px;" controls>
                        <source src="@Url.Content(item.ContentUrl)" type="video/mp4" />
                    </video>
                </div>
            </div>
        }
    </div>
</body>
</html>

在控制器中獲取視頻的代碼:

[HttpGet]
public ActionResult GetVideosUser(UserViewModel user)
  {
     List<VideoViewModel> videoViewModels = new List<VideoViewModel>();
     string userName = user.FirstName + " " + user.LastName;
     string pathString = Path.Combine(@"path", userName);
     List<Video> videos = _videoLogic.GetVideos();
     foreach (Video video in videos)
     {
       VideoViewModel videoViewModel =  new VideoViewModel(video);
       videoViewModels.Add(videoViewModel);
     }
return View("ViewerVideoList", videoViewModels);
  }

此代碼將數據正確上傳到我的數據庫,並將正確的文件上傳到我的視頻文件夾。 它還正確地獲取了上述 ContentUrl。 我怎樣才能讓這個視頻正確播放? 提前謝謝了!

代碼圖片:![代碼]: https : //imgur.com/a/xdprrAw

Chrome 中的 URL:/wwwroot/video/Jesse%20Oosterwijk/WhatsApp%20Video%202019-12-04%20at%2018.04.49.mp4

![ChromeCode]: https://imgur.com/a/kCM3p71

![FileIsThere]: https://imgur.com/a/WaXQtUd

CorrectExtensions https://imgur.com/a/KTI2vSv

做了一些研究,發現由於安全原因,firefox 和 chrome 無法從您的磁盤播放視頻。

您可以嘗試通過相對於Web 根目錄的路徑而不是物理路徑來訪問這些視頻文件。

Name = "user1",
ContentUrl = "~/videos/user1/movie.mp4"

測試結果

在此處輸入圖片說明

注意:出現問題時,如果您在瀏覽器中查看 Console 或 html 源代碼,您可能會發現文件路徑如下所示。

在此處輸入圖片說明

找到了解決問題的方法。 通過依賴注入,我可以向我的視頻控制器添加一個 IHostingEnvironment。 這樣我可以更輕松地將視頻保存到我的 webroot。

添加托管環境:

public class VideoController : Controller
{

    private readonly VideoLogic _videoLogic;
    private readonly CategoryLogic _categoryLogic;
    private readonly ReportLogic _reportLogic;
    private readonly CommentLogic _commentLogic;
    private readonly UserLogic _userLogic;
    private readonly IHostingEnvironment _environment;

    public VideoController(VideoLogic videoLogic, CategoryLogic categoryLogic, ReportLogic reportLogic, CommentLogic commentLogic, UserLogic userLogic, IHostingEnvironment environment)
    {
        _videoLogic = videoLogic;
        _categoryLogic = categoryLogic;
        _reportLogic = reportLogic;
        _commentLogic = commentLogic;
        _userLogic = userLogic;
        _environment = environment;
    }

在保存視頻的代碼中:

[HttpPost]
public async Task<IActionResult> UploadVideo(VideoViewModel video, IFormFile file)
{
    if (file.Length > 0)
    {
        try
        {
            int userId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Sid)?.Value);
            string userName = (User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Name).Value);
            string folder = Path.Combine(_environment.WebRootPath, "video");
            string url = @"\video\" + userName + @"\" + file.FileName;
            string pathString = Path.Combine(folder, userName);
            if (!Directory.Exists(pathString))
            {
                Directory.CreateDirectory(pathString);
            }
            var filePath = Path.Combine(pathString, file.FileName);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
                _videoLogic.SaveVideo(new Video(userId, video.VideoId, video.Description, file.FileName, DateTime.Now, url, video.CategoryId));
            }
        }
        catch (Exception ex)
        {
            ViewBag.Message = "ERROR: " + ex.Message.ToString();
        }
    }
    else
    {
        ViewBag.Message = "You have not specified a file.";
    }
    return RedirectToAction("UploadVideo");
}

之后,您可以從數據庫中獲取視頻並從那里獲取 url! 感謝所有的幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM