如何将mvc 5中的多个文件上传到服务器并使用实体框架

时间:2015-07-30 20:50:15

标签: c# .net asp.net-mvc entity-framework asp.net-mvc-5

我正在尝试将文件列表保存到文件系统和EF的路径。我还没有在网上找到完整的教程,所以我已经把几篇博客文章搞砸了,以找出我需要的内容。我可以保存1个文件但我无法保存多个文件。我知道为什么。这是因为列表在每个文件后都会重新初始化。我试图将事物移入和移出范围,并尝试以其他方式初始化变量。有人可以看看我的控制器,看看我能做些什么来修复?

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Exclude = "Id")] Incident incident, IEnumerable<HttpPostedFileBase> upload)
    {
        if (ModelState.IsValid)
        {

            if (upload != null)
            {

                int MaxContentLength = 1024 * 1024 * 10; //10 MB
                string[] AllowedFileExtensions = new string[] { ".jpg, ", ".gif", ".png", ".pdf", ".doc", "docx", "xls", "xls" };

                foreach (var file in upload)
                {
                    if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal)).ToLower()))
                    {
                        ModelState.AddModelError("Upload", "Document Type not allowed. Please add files of type: " + string.Join(", ", AllowedFileExtensions));
                    }
                    else if (file.ContentLength > MaxContentLength)
                    {
                        ModelState.AddModelError("Upload", "Your file is too large. Maximum size allowed is: " + MaxContentLength + " MB");
                    }
                    else
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                        file.SaveAs(path);
                        var photo = new FilePath
                        {
                            FileName = Path.GetFileName(file.FileName),
                            FileType = FileType.Document
                        };
                        incident.FilePaths = new List<FilePath> { photo };
                    }
                }
                ModelState.Clear();
            }

            db.Incidents.Add(incident);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

1 个答案:

答案 0 :(得分:0)

在循环之前初始化列表:

incident.FilePaths = new List<FilePath>();
foreach(var file in upload)
{
    // your code except last line
    incident.FilePaths.Add(photo); 
}
// rest of your code