尝试使用ASP.NET Core将文件上传到数据库

时间:2018-09-12 13:00:20

标签: c# asp.net-core

我正在努力使用ASP.NET Core将文件加载到数据库中。我可能在做错什么。

这就是我的模型中的内容

namespace BeeshoekCWPortal.Models
{
    public class CWRecords
    {

    public int Id { get; set; }

    public string RecordName { get; set; }
    public byte[] Document { get; set; }

    [DisplayFormat(DataFormatString ="{0:d}")]
    public DateTime DateAdded { get; set; }

    public int CWId { get; set; }

    [ForeignKey("CWId")]
    public virtual ContingentWorker CW { get; set; }
    }
 }

这就是我的ViewModel中的内容

namespace BeeshoekCWPortal.ViewModel
{
   public class CWandRecordsViewModel
  {

    public int CWId { get; set; }
    public string Title { get; set; }
    public string FullNames { get; set; }
    public string Surname { get; set; }
    public string DateofBirth { get; set; }
    public string IdPassportNumber { get; set; }
    public string Gender { get; set; }
    public string Race { get; set; }
    public string Nationality { get; set; }
    public IFormFile Document { get; set; }

    public CWRecords NewRecordObj { get; set; }
    public IEnumerable<CWRecords> PastRecordObj { get; set; }
    }
  }

我坚信我在Controller中做错了事。

    //POST : Services/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CWandRecordsViewModel model)

    {            
        if (ModelState.IsValid)
        {
            {
                model.NewRecordObj.CWId = model.CWId;
                model.NewRecordObj.DateAdded = DateTime.Now;
                _db.Add(model.NewRecordObj);
                await _db.SaveChangesAsync();
            };
            using (var memoryStream = new MemoryStream())
            {
                await model.Document.CopyToAsync(memoryStream);

            };
            return RedirectToAction(nameof(Create), new { CWId = model.CWId });


        }
        var CW = _db.ContingentWorkers.FirstOrDefault(c => c.Id == model.CWId);
        var newModel = new CWandRecordsViewModel
        {
            CWId = CW.Id,
            Title = CW.Title,
            FullNames = CW.FullNames,
            Surname = CW.Surname,
            DateofBirth = CW.DateofBirth,
            IdPassportNumber = CW.IdPassportNumber,
            Gender = CW.Gender,
            Race = CW.Race,
            Nationality = CW.Nationality,
            PastRecordObj = _db.CWRecords.Where(r => r.CWId == model.CWId).OrderByDescending(r => r.DateAdded).Take(5)
        };
        return View(newModel);
    }

如何修复控制器,以便可以将文件上传到数据库。

1 个答案:

答案 0 :(得分:1)

首先,您不应在视图模型内部拥有要创建的新实体作为属性。您应该将它们分开,并且仅在实际创建实体时创建它。

然后,为了存储来自上载文件的数据,您将必须将其存储在实体内部。现在,您要做的只是将数据从上传的文件复制到内存流中。然后,您将丢弃内存流,因此所有数据都将丢失,并且永远不会到达实体或数据库(在读取文件之前, 还保存了数据库更改)

您的代码应如下所示:

if (ModelState.IsValid)
{
    var newRecordObj = new CWRecords
    {
        CWId = model.CWId,
        DateAdded = DateTime.Now,
    };

    using (var memoryStream = new MemoryStream())
    {
        await model.Document.CopyToAsync(memoryStream);
        newRecordObj.Document = memoryStream.ToArray();
    };

    _db.Add(newRecordObj);
    await _db.SaveChangesAsync();

    return RedirectToAction(nameof(Create), new { CWId = model.CWId });
}