Register image with others data in api crud

63 Views Asked by At

I am workin in a side project and this project is a CRUD API in ASP.NET Core, until now that is the model of my datas

public class Book
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public string Author { get; set; }
     public string Genre { get; set; }
 }

Now I need to add a new data, the book's image.

[HttpPost]
public async Task<ActionResult<List<Book>>> AddBook(Book book)
{
    var resut = await _bookRepository.AddBook(book);
    return Ok(resut);
}

This is my post method. That code have a repository pattern structure with the code in bellow:

public async Task<List<Book>> AddBook(Book book)
 {
     _context.Books.Add(book);
     await _context.SaveChangesAsync();
     return await _context.Books.ToListAsync();
 }

Do you guys have any ideas how can i implement a image data on this code ?

I heard that I can use the FormData but I dont get it how can I do that

1

There are 1 best solutions below

0
Yuning Duan On

Based on your description

I heard that I can use the FormData but I dont get it how can I do that

You can utilize an IFormFile property to obtain the file, and use a byte[] property like CoverImage to store it in the database. Additionally, in the controller, you can use the [FromForm] attribute to specify that it should fetch data from the HTTP form submission. Here's an example I've provided for your reference:

My bookmodel:

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

       
    public string Name { get; set; }

  
    public string Author { get; set; }

   
    public string Genre { get; set; }

      
    public byte[] CoverImage { get; set; } 

}

My inputmodel:

public class BookWithImageInputModel
    {
        public string Name { get; set; }
        public string Genre { get; set; }
        public string Author { get; set; }
        public IFormFile CoverImageFile { get; set; }
    }

My controller:

[HttpPost]
public async Task<IActionResult> AddBook([FromForm] BookWithImageInputModel inputModels)//
{

    if (inputModels == null )
    {
        return BadRequest("Invalid input");
    }
    var book = new Book
    {
        Name = inputModels.Name,
        Author = inputModels.Author,
        Genre = inputModels.Genre
    };
    using (var memoryStream = new MemoryStream())
    {
        await inputModels.CoverImageFile.CopyToAsync(memoryStream);
        book.CoverImage = memoryStream.ToArray();
    }
    var addedBook = await _bookRepository.AddBookAsync(book);

    return Ok(addedBook);
}

MY BookRepositoryEF:

async Task<List<Book>> IBookRepository.AddBookAsync(Book book)
{
     _context.Books.Add(book);
     await _context.SaveChangesAsync();
     var books = await _context.Books.ToListAsync();
     return books;
}

MY BookRepositoryinterface:

Task<List<Book>> AddBookAsync(Book book);

When I add data:

enter image description here