Home > database >  How to implement model binded upload in asp.net core mvc 6?
How to implement model binded upload in asp.net core mvc 6?

Time:04-25

Nearly every tutorial about about this is oudated, so even though I looked for a long time I couldn't find anything that answered my query and still worked.

I have a model like so

 public class 
    {
        public int Id { get; set; }

        public string Title {get;set;}
        
        public string Author {get;set;}
    }

and I want to add another variable for PDF file. So users can upload pdf files of each book, and download from them if possible. from my understanding something like public IFormFile File { get; set; } will suffice. I have figured the view to be something that involves specific enctypes, asp-for etc so that isn't really what I care about.

My question is about a controller that does what I want, which is uploading a file only for that model entry in database. I have seen some use DBcontext.Model.add(entryname), but usually it is prefaced by stuff I either can't make sense of or make work. Beyond that I am clueless.

CodePudding user response:

I write a simple demo here about how to upload PDF file and save it in database,I have written annotations in many places and hope it can help you to solve your problem.

First, You use IFormFile to upload files, but the database can't directly hold this type of data, So I choose to convert it to byte[] and then store in the Database.

code:

Model

//I use this model to create a database

public class Book
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Author { get; set; }

        public byte[] book { get; set; }
    }


//Because I need data of type IFormFile to upload the file, So i create BookViewModel,
//I will use this model to pass data from view to controller 

public class BookViewModel
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Author { get; set; }

        public IFormFile book { get; set; }
    }

DataContext

//create the database
public class ApplicationContext : DbContext
    {
        public ApplicationContext(DbContextOptions<ApplicationContext> options): base(options)
        {

        }

        public DbSet<Book> books { get; set; }
    }

controller

public class HomeController : Controller
    {
       //Use dependency injection to inject the database you just created into the controller

        private readonly ApplicationContext _context;

        public HomeController(ApplicationContext context)
        {
            _context = context;
        }

        public IActionResult UploadBook()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> UploadBook(BookViewModel model)
        {
            //Check if pdf file exists
            if (model.book != null && model.book.Length>0)
            {
                //Instantiate Book, then assign the values ​​of Author and Title in viewmode to Book
                Book bookModel = new Book()
                {
                    Author = model.Author,
                    Title = model.Title,
                };

                //Convert PDF file to byte[] and Give the byte[] to book
                using (var target = new MemoryStream())
                {
                   model.book.CopyTo(target);
                    bookModel.book = target.ToArray();
                }

                //use EF CORE and linq to add data and save .
                _context.books.Add(bookModel);
                _context.SaveChanges();

                return RedirectToAction("Success");
            }

            return RedirectToAction("Fail");
        }
  }

View

@model BookViewModel
<form method="post" enctype="multipart/form-data" asp-action="UploadBook">
    <div >
        <label asp-for="@Model.Title"></label>
        <input asp-for="@Model.Title" />
    </div>
    <div >
        <label asp-for="@Model.Author"></label>
        <input asp-for="@Model.Author" />
    </div>
    <div >
        <label asp-for="@Model.book"></label>
        <input asp-for="@Model.book" />
    </div>
    <button type="submit">upload</button>
</form>

Result:

Finally, You can see I have upload the file and save it in database successfully.

enter image description here

  • Related