简体   繁体   中英

How to upload video in ASP.NET MVC 5 and pass the video file from a view to a method?

I'm writing an MVC 5 web application to update blog posts. I want to be able to have the user upload a video to the content folder and then store the filename as a string in the database. However, I seem to be missing one essential piece though.

I have a method to update the posts which is working except for the video part.

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);

I have created a class for the Video with one property.

public class Video
{
    public HttpPostedFileBase File { get; set; }
}

Then a method in the same class as the Update method to upload the video and return the filename.

[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;
}

Then I have a View for the Update method but I don't know how to get the video object from this View into the Update method so that I can pass it to the UploadVideo method.

<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>

Using <input type="file" name="video" /> results in the video object being null when passed into the Update method.

How would you pass in the video file to the Update method with all the other text data set in the View such as dateTime , title , tags and body ?

Below is snippet, i just typed here to give an idea, you can understand, if you need more info let me know

    [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");
    }

The accepted answer solved the problem of getting the video file from the view into the method. I'm just posting what I changed in my code in case it helps anyone.

[HttpPost]
public string UploadVideo(HttpFileCollection video)
{
    if (video.Count <= 0) return null;
    var fileName = Path.GetFileName(video.Get(0).FileName);
    var path = Path.Combine(Server.MapPath("~/Content/Videos"), fileName);
    // save video here
    return fileName;
}

[ValidateInput(false)]
public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags)
{
    if (!IsAdmin)
    {
        return RedirectToAction("Index");
    }

    var post = GetPost(id); // get the post object

    var video = System.Web.HttpContext.Current.Request.Files;

    post.Title = title;
    post.Body = body;
    post.DateTime = dateTime;
    post.Tags.Clear();
    post.VideoFileName = UploadVideo(video);
    // continued, more code
}

public class Video
{
    public HttpFileCollection File { get; set; }
}

I just added enctype attribute to the form in the View

<form action="@Href("~/Posts/Update")" method="post" id="postForm" enctype="multipart/form-data">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM