Wednesday, February 27, 2019

Best practice with sending JSON + image in EF POST

I've got an API i'm working on and currently I have two POST's. One that accepts JSON and one the accepts IFormFile.

[HttpPost("furniture")] public IActionResult AddNewFurniture(Furniture newFurniture) { if(newFurniture == null) { return BadRequest(); } var finalFurniture = new Furniture() { Name = newFurniture.Name, UID = newFurniture.UID, CategoryId = newFurniture.CategoryId, Cost = newFurniture.Cost, PurchasedFrom = newFurniture.PurchasedFrom, DatePurchased = newFurniture.DatePurchased, HouseId = newFurniture.HouseId, Turns = newFurniture.Turns }; _furnitureInfoRepository.AddNewFurniture(finalFurniture); return Ok(); } [HttpPost("upload")] public async Task<IActionResult> UploadFile(IFormFile image) { var furnitureImage = new FurnitureImage(); if (ModelState.IsValid) { if (image != null && image.Length > 0) { var fileName = Path.GetFileName(image.FileName); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\NewFolder", fileName); using (var fileSteam = new FileStream(filePath, FileMode.Create)) { await image.CopyToAsync(fileSteam); } //Hard coding the furnitureId for testing purposes. furnitureImage = new FurnitureImage() { PictureInfo = fileName, FurnitureId = 9 }; } } _furnitureInfoRepository.AddNewFurnitureImage(furnitureImage); return Ok(furnitureImage); } 

The issue I am facing is that the FurnitureImage and Furniture will be related by the furnitureId, which is generated by the database. The user will be sending the image and text over as one. In the above case, how would I go about saving AddNewFurniture and also passing along it's new furnitureId to Uploadfile.

My next question, is this the best way to do this? Would it be better to send them over as two parameters to the same furniture endpoint and then in the furnitureInfoRepository save the furniture type to the furniture table, return the newly created furniture and pass it's ID along with the furnitureImage info into the upload method? What would that look like? Is there is some sort of ModelBinding I have to introduce if I decide to go this route?

Best practice with sending JSON + image in EF POST Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team