我在 MVC4 C# 中创建一个网站,它允许您将文件上传到项目文件夹内的文件夹中,由于某种原因控制器找不到上传的文件。“db.music.Add(newsong)”不会将歌曲路径和名称添加到数据库中。这是项目的视图、控制器和模型。感谢您的帮助!
Index.cshtml - 查看
@{
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 - 控制器
[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 - 模型
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; }
}
}