Facebook
From Bistre Iguana, 6 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 289
  1. // POST: api/Books
  2.         [HttpPost]
  3.         [AllowAnonymous]
  4.         //[Authorize(Roles = "Admin")]
  5.         public async Task<IActionResult> PostBook([FromBody] Book book, IFormFile image)
  6.         {
  7.             if (image.Length > 0)
  8.             {
  9.                 string returnPath = Path.Combine("images\\booksImages", image.FileName);
  10.                 string path = Path.Combine(_env.WebRootPath, returnPath);
  11.  
  12.                 if (System.IO.File.Exists(path))
  13.                 {
  14.                     return BadRequest("File with that name already exists.");
  15.                 }
  16.  
  17.                 using (var fs = new FileStream(path, FileMode.Create))
  18.                 {
  19.                     await image.CopyToAsync(fs);
  20.                 }
  21.  
  22.                 if (ModelState.IsValid)
  23.                 {
  24.                     book.ImagePath = returnPath;
  25.                     _context.Books.Add(book);
  26.                     await _context.SaveChangesAsync();
  27.  
  28.                     return CreatedAtAction("GetBook", new { id = book.BookId }, book);
  29.                 }                
  30.             }
  31.  
  32.             return BadRequest(ModelState);
  33.         }