Why can I upload files via the Postman application, but when I use Microsot, I cannot upload where is the problem with the following code?
Model is:
- public class Book
- {
- [Key]
- public int BookId { get; set; }
- [Display(Name = "Book name")]
- [Required(ErrorMessage = "Data feild is required")]
- public string BookName { get; set; }
- [Display(Name ="Book details")]
- [Required(ErrorMessage = "Data feild is required")]
- public string BookDetails { get; set; }
- [Display(Name = "Publish date")]
- [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
- [Required(ErrorMessage = "Data feild is required")]
- public DateTime BookPdate { get; set; }
- [Display(Name = "Book name")]
- [Required(ErrorMessage = "Data feild is required")]
- [ForeignKey("Author")]
- public int AuthortId { get; set; }
- public virtual Author Author { get; set; }
- public string ImagePath { get; set; }
- [NotMapped]
- public IFormFile ImageFile { get; set; }
- }
Client controller method:
- [HttpPost]
- public IActionResult AddOrEdit(Book book)
- {
- if (book.BookId == 0)
- {
- HttpResponseMessage resp = GlobalApiClient.webApiClient.PostAsJsonAsync("Books", book).Result;
- TempData["SuccessMsg"] = "Saved Successfully ... ";
- return RedirectToAction("Index");
- }
- else
- {
- HttpResponseMessage resp = GlobalApiClient.webApiClient.PutAsJsonAsync("Books/" + book.BookId , book).Result;
- if (resp.IsSuccessStatusCode)
- {
- TempData["SuccessMsg"] = "Updated Successfully ... ";
- }
- else
- {
- TempData["SuccessMsg"] = "Updated not complete ... ";
- }
- return RedirectToAction("Index");
- }
- }
Api controller method:
-
- [HttpPut("{id}")]
- public async Task<IActionResult> Put(int id,[FromBody] Book book)
- {
- if (ModelState.IsValid)
- {
- try
- {
- if (id == book.BookId)
- {
- string fileName = book.ImagePath;
- if (book.ImageFile.Length > 0)
- {
- string path = hosting.WebRootPath + "\\Uploads\\";
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- using (FileStream fileStream = System.IO.File.Create(path + book.ImageFile.FileName))
- {
- book.ImageFile.CopyTo(fileStream);
- fileStream.Flush();
- }
- }
- book.ImagePath = fileName;
- await bookRepo.Update(book);
- return Ok();
- }
- return NotFound();
- }
- catch (Exception)
- {
- return BadRequest();
- }
- }
- return BadRequest();
- }