简体   繁体   中英

How to upload multiple files in mvc 5 to server and store file's path with Entity Framework

I am trying to save a list of files to the file system and the path to EF. I haven't found a complete tutorial online so I've mashed up a couple of blog posts to scope out what I need. I can save 1 file but I can't save multiple files. I know why though. It is because the list gets reinitialized after every file. I've tried to move things in and out of scope and tried initializing variables in other ways. Can someone take a look at my controller and see what I can do to fix?

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

Initialize the list before loop:

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

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