c# – 如何在ASP.NET MVC 5中上传视频并将视频文件从视图传递给方法?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 如何在ASP.NET MVC 5中上传视频并将视频文件从视图传递给方法?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2500字,纯文字阅读大概需要4分钟。
内容图文
![c# – 如何在ASP.NET MVC 5中上传视频并将视频文件从视图传递给方法?](/upload/InfoBanner/zyjiaocheng/794/934a872bb4df4fec95cb1f7d50a5787e.jpg)
我正在编写一个MVC 5 Web应用程序来更新博客文章.我希望能够让用户将视频上传到内容文件夹,然后将文件名作为字符串存储在数据库中.但是,我似乎错过了一件必不可少的作品.
我有一种方法来更新除视频部分以外的其他帖子.
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;
}
然后我有一个View for the Update方法,但我不知道如何将视图对象从此View中导入Update方法,以便我可以将它传递给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方法时,视频对象为null.
如何将视频文件传递给Update方法,并在视图中设置所有其他文本数据,例如dateTime,title,tags和body?
解决方法:
下面是片段,我只是在这里输入一个想法,你可以理解,如果你需要更多信息,请告诉我
[HttpPost]
public ActionResult UploadFile()
{
var httpPostedFile = Request.Files[0];
if (httpPostedFile != null) {
// Validate the uploaded file if you want like content length(optional)
// Get the complete file path
var uploadFilesDir = System.Web.HttpContext.Current.Server.MapPath("~/Content/Videos");
Directory.CreateDirectory(uploadFilesDir);
var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
return Content("Uploaded Successfully");
}
内容总结
以上是互联网集市为您收集整理的c# – 如何在ASP.NET MVC 5中上传视频并将视频文件从视图传递给方法?全部内容,希望文章能够帮你解决c# – 如何在ASP.NET MVC 5中上传视频并将视频文件从视图传递给方法?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。