我正在編寫一個MVC 5 web應用程序來更新博客文章。我希望能夠讓用戶將視頻上傳到內容文件夾,然後將文件名作爲字符串存儲在數據庫中。不過,我似乎錯過了一件重要的作品。如何在ASP.NET MVC 5中上傳視頻並將視圖中的視頻文件傳遞給方法?
我有一個方法來更新除了視頻部分正在工作的職位。
public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags, Video video)
{
if (!IsAdmin)
{
return RedirectToAction("Index");
}
var post = GetPost(id); // get the post object
post.Title = title;
post.Body = body;
post.DateTime = dateTime;
post.Tags.Clear();
post.VideoFileName = UploadVideo(video);
我爲視頻創建了一個類,其中包含一個屬性。
public class Video
{
public HttpPostedFileBase File { get; set; }
}
然後在同一類的Update
方法上傳的視頻,並返回文件名的方法。
[HttpPost]
public string UploadVideo(Video video)
{
if (video.File.ContentLength <= 0) return null;
var fileName = Path.GetFileName(video.File.FileName);
if (fileName == null) return null;
var path = Path.Combine(Server.MapPath("~/Content/Videos"), fileName);
video.File.SaveAs(path);
return fileName;
}
然後我對更新方法的看法,但我不知道怎麼去從這個視圖進入更新方法的視頻對象,這樣我可以把它傳遞給UploadVideo
方法。
<form action="@Href("~/Posts/Update")" method="post" id="postForm">
@if(Model.Id != -1)
{
<input type="hidden" name="id" value="@Model.Id"/>
}
@{ var dateTime = Model.DateTime.Year > 2000 ? Model.DateTime : DateTime.Now; }
<input type="text" name="dateTime" value="@dateTime "/> Date<br />
<input type="text" name="title" value="@Model.Title " /> Title<br />
<input type="text" name="tags" value="@ViewBag.Tags " /> Tags<br />
<textarea name="body" rows="10" cols="80">@Model.Body</textarea><br />
<br/>
<br/>
<input type="file" name="video" />
<br/>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
使用<input type="file" name="video" />
導致視頻對象在傳遞到Update方法時爲空。
你怎麼會在視頻文件傳遞到更新方法與所有其他文本數據的視圖,例如dateTime
,title
,tags
和body
設置?
添加'form'屬性'ENCTYPE = 「的multipart/form-data的」',你必須捕捉'視頻文件HttpContext.Current.Request.Files' in ActionResult Update()' – 2014-10-18 21:56:20
@Venkata我添加了'enctype',但是如何使用HttpContext捕獲視頻文件? – 2014-10-18 22:08:41
出於某種原因,我不得不使用'System.Web.HttpContext.Current.Request.Files',它不會通過在類文件的頂部添加'using System.Web'來工作。 – 2014-10-18 22:16:23