public ActionResult <Product> UploadFile() { //get From header the files //article https://www.talkingdotnet.com/upload-file-angular-5-asp-net-core-2-1-web-api/ var file = Request.Form.Files[0]; var http = Request; string webRootPath = environment.WebRootPath; var imagePath = FileHttp.HttpUploadFile(file, webRootPath); Product p = new Product { PicPath = imagePath, Name = Request.Form["Name"] }; return(p); }
public async Task <ActionResult <Product> > PostProduct() { //file upload var file = Request.Form.Files[0]; string webRootPath = hostingEnvironment.WebRootPath; string picPath = FileHttp.HttpUploadFile(file, webRootPath); picPath = "Upload/" + picPath; Product product = new Product { Name = Request.Form["name"], PicPath = picPath, Price = int.Parse(Request.Form["price"]), CategoryName = Request.Form["categoryName"] }; _context.products.Add(product); await _context.SaveChangesAsync(); //return CreatedAtAction("GetProduct", new { id = product.Id }, product); return(Ok()); }
public async Task <IActionResult> PutProduct(int id) { //no you gonna path it in form data // find and get the product by id var product = await _context.products.FindAsync(id); // checked if it exixt if (id != int.Parse(Request.Form["id"])) { return(NotFound()); } if (product == null) { return(NotFound()); } // old image path string picPath = product.PicPath; // check if user update image if (Request.Form.Files.Count > 0) { string webRootPath = hostingEnvironment.WebRootPath; //delete previos image FileHttp.HttpDeleteFile(product.PicPath, webRootPath); //add new image var file = Request.Form.Files[0]; picPath = FileHttp.HttpUploadFile(file, webRootPath); // Edit image path picPath = "Upload/" + picPath; } product.Name = Request.Form["name"]; product.Price = int.Parse(Request.Form["price"]); product.PicPath = picPath; _context.Entry(product).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.Id)) { return(NotFound()); } else { throw; } } return(NoContent()); }