在MVC4中上传文件

时间:2013-06-11 21:00:52

标签: asp.net-mvc-4

我正在使用MVC4 C#创建一个网站,它允许您将文件上传到项目文件夹中的文件夹, 由于某种原因,控制器无法找到上传的文件。 “db.music.Add(newsong)”不会将歌曲路径和名称添加到DB。这是项目的视图,控制器和模型。 谢谢你的帮助!


Index.cshtml - VIEW

@{
ViewBag.Title = "Index";
}

<h2>Your Music</h2>

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" >
    <input type="submit" />

MusicController.cs - CONTROLLER

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{

   if (file.ContentLength > 0)
       {
            var fileName = Path.GetFileName(file.FileName);
            MVPDB db = new MVPDB();
            UploadMusic newsong = new UploadMusic();
            newsong.userId = 11;
            newsong.songName = file.FileName.ToString();
            newsong.songPath = Path.GetFileName(file.FileName).ToString();

            db.music.Add(newsong);
            db.SaveChanges();

            var path = Path.Combine(Server.MapPath("~/UserFiles/"), fileName);
            file.SaveAs(path);
        }

            return RedirectToAction("Index");
        }

Music.cs - MODEL

namespace MVP.Models
{
public class Music
    {
        [Key]
        public int userId { get; set; }
        public string songName { get; set; }
        public string songPath { get; set; }

    }
public class UploadMusic
    {
        [Required]
        public int userId { get; set; }
        [Required]
        public string songName { get; set; }
        [Required]
        public string songPath { get; set; }


    }
}

1 个答案:

答案 0 :(得分:4)

您的表单不包含操作。试试这个

@using (Html.BeginForm("Index", "Music", FormMethod.Post, new { enctype = "multipart/form-data" }))