首页 > 解决方案 > 多文件上传仅存储数据库中的最后一个文件 Asp .Net Core MVC

问题描述

我正在尝试上传多个文件。文件已正确上传,但在数据库中,仅存储最后一个文件这是我的 post 方法代码

  public async Task<IActionResult> ApplyLeave(ApplyLeaveViewModel model)
        {

            string uniqueFileName = null;
            if (model.File != null && model.File.Count > 0)
            {
                foreach (IFormFile file in model.File)
                {
                    string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "dist/files");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    file.CopyTo(new FileStream(filePath, FileMode.Create));
                }

                var leaveApplied = _mapper.Map<LeaveViewModel>(model);
                leaveApplied.FilePath = uniqueFileName;
                await _leavePageService.AddNewLeave(leaveApplied);
             
              
            }

            return View(model);
        }    }

这部分 ApplyLeaveViewModel 对应离开属性

        public string Reason { get; set; }
        public string Comment { get; set; }
        public List<IFormFile> File { get; set; }

这是被映射并将数据存储在数据库中的 LeaveViewModel

        public string FilePath { get; set; }

我知道 uniqueFileName 是一个字符串,它一次只存储一个值,因此它显示最后一个值。怎么办,让所有上传的文件都存入数据库

标签: asp.net-core-mvc

解决方案


我知道 uniqueFileName 是一个字符串,它一次只存储一个值,因此它显示最后一个值。

您在结束后获得uniqueFileNameforeach (IFormFile file in model.File),因此它的值是最后一个文件的名称

  1. 第一个解决方案是你不要改变你的 Model,也就是public string FilePath {get; set;}用来存放多个文件的 uniqueFileName

    1. 您需要连接所有的uniqueFileNames,并用一个字符(如|)分隔uniqueFileNames。
      •   string allfilesPath = null;
          if (model.File != null && model.File.Count > 0)
          {
              foreach (IFormFile file in model.File)
              {
                  ... ...
                  allfilesPath += "|" + uniqueFileName;
              }
              var leaveApplied = _mapper.Map<LeaveModel>(model);
              leaveApplied.AllFiles = allfilesPath;
        
    2. 下次获取值时,需要使用String.Split 方法字符串进行拆分,得到每个 uniqueFileName。
  2. 第二种解决方案是:可以添加一个名为FileModel的新模型,用于存储文件信息,并且可以设置导航属性,使LeaveModel 和 FileModel具有一对多的关系

    1. 我写了一个例子,你可以参考一下。

    2. 模型

       public class LeaveModel
       {
           [Key]
           public int LeaveId { get; set; }
           public string Reason { get; set; }
           public string Comment { get; set; }
           public List<FileModel> AllFiles { get; set; }
       }
       public class FileModel
       {
           [Key]
           public int FileId { get; set; }
           public string FilePath { get; set; }
           public int? LeaveId { get; set; }
       }
       public class ApplyLeaveViewModel
       {
           public string Reason { get; set; }
           public string Comment { get; set; }
           public List<IFormFile> File { get; set; }
       }
      
    3. 离开控制器

       public class LeaveController : Controller
       {
           public IWebHostEnvironment _webHostEnvironment;
           private readonly IMapper _mapper;
           public DailyCoreMVCDemoContext _db;
           public LeaveController(IWebHostEnvironment webHostEnvironment, IMapper mapper, DailyCoreMVCDemoContext db)
           {
               _mapper = mapper;
               _webHostEnvironment = webHostEnvironment;
               _db = db;
           }
           public IActionResult Index()
           {
               return View();
           }
           public IActionResult ApplyLeave(ApplyLeaveViewModel model)
           {
               string uniqueFileName = null;
               if (model.File != null && model.File.Count > 0)
               {
                   List<FileModel> fileModels = new List<FileModel>();
                   foreach (IFormFile file in model.File)
                   {
                       string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "dist/files");
                       if (!Directory.Exists(uploadsFolder))
                       {
                           Directory.CreateDirectory(uploadsFolder);
                       }
                       uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;
                       string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                       file.CopyTo(new FileStream(filePath, FileMode.Create));
                       fileModels.Add(new FileModel { FilePath = uniqueFileName });
                   }
                   var leaveApplied = _mapper.Map<LeaveModel>(model);
                   leaveApplied.AllFiles = fileModels;
                   _db.LeaveModels.Add(leaveApplied);
                   _db.SaveChanges();
               }
               return RedirectToAction("Index");
           }
       }
      
    4. 指数

       @model WebApplication24.Models.ApplyLeaveViewModel
       <form asp-controller="Leave" asp-action="ApplyLeave" method="post" enctype="multipart/form-data">
       <input asp-for="Comment"/>
       <input asp-for="Reason"/>
       <input asp-for="File" type="file" multiple/>
           <button type="submit">submit</button>
       </form>
      
    5. 结果

      在此处输入图像描述


推荐阅读