Click here to Skip to main content
14,773,364 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Can someone assist me I have a challenge here am working on core website that has a backend app and frontend app, on the backend I have a page that is used by admin to upload the images and also the documents like(PDF, word or excel) and save in SQL database so that the frontend can be able to ready the uploaded information. My challenge is to use IFormFile to record both values for the image and document that the user uploaded on the form, my code is only working when you upload one record at time not both. below is the code that I’m using.

What I have tried:

This is my Model
public class tblFile
    public int id { get; set; }
    public string Name { get; set; }
    public byte[] Img { get; set; }
    public string ContentType { get; set; }
    public byte[] Data { get; set; }
    public DateTime CreatedOn { get; set; }

This my Controller
public async Task<IActionResult> Create(tblFile tblFile, List<IFormFile> Data)
    if (ModelState.IsValid)
        foreach (var item in Data)
            if (item.Length > 0)
                using var tl = new MemoryStream();
                //bytes == item.CopyTo(tl);
                tblFile.Data = tl.ToArray();

        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    return View(tblFile);
Updated 23-Nov-20 23:46pm
Sandeep Mewara 24-Nov-20 4:36am
Your shared code does not share much related to problem you share.

Perhaps following documentation could be of help:
It has details of how to upload using IFormFile.

1 solution

You are uploading and adding a single record. If you upload multiple files, you overwrite the file data on that record with each item in the list, leaving just the last file.

You need to add a record for each file in the list.

Also, most of your model properties don't seem to be intended to be editable by the user, so it doesn't make sense to use that model for your view.
public async Task<IActionResult> Create(List<IFormFile> Data)
    if (!ModelState.IsValid)
        return View();
    foreach (var item in Data)
        if (item.Length == 0) continue;
        using var ms = new MemoryStream();
        await item.CopyToAsync(ms);
        _context.AddAsync(new tblFile
            Name = Path.GetFileName(item.FileName),
            ContentType = item.ContentType,
            Data = ms.ToArray(),
            CreatedOn = DateTime.UtcNow,
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900