osyris zosar

osyris zosar

  • NA
  • 289
  • 26.7k

Uploading Image with API and javascript

May 16 2021 9:41 PM
I understand how to upload images using mvc with razor pages
 
Now i would like to upload a image using Javascript .
 
Javascript code:
  1. function CreateProduct() {    
  2.     
  3.     event.preventDefault();    
  4.     const Titleform = document.getElementById("TitleFelt");    
  5.     const Priceform = document.getElementById("priceFelt");    
  6.     const quantityform = document.getElementById("Quantityfelt");    
  7.     
  8.     const file = document.getElementById("fileupload"); //the File Upload input    
  9.     const formdata = new FormData();    
  10.     
  11.     formdata.append("userpic", file.files[0],'Test1.jpg');    
  12.     };    
  13.     fetch(url, {    
  14.         method: 'POST',    
  15.         headers: {    
  16.             'Accept''application/json',    
  17.             'Content-Type''application/json'    
  18.         },    
  19.     
  20.         body: formdata    
  21.     })    
  22.         .then(response => response.json())    
  23.         .then(result => {    
  24.             console.log('succes', result);    
  25.         })     
  26.         .then(() => {    
  27.             GetProducts();    
  28.     
  29.         })    
  30.             .catch(error => console.log('unable to do something', error));    
  31. }  
and my asp net core action:
  1. [HttpPost]    
  2. public async Task<IActionResult> PostProduct(IFormFile formFile)    
  3. {    
  4.     Product pr = new Product()    
  5.     {    
  6.          Title = "test",    
  7.          Price = 2,    
  8.          FilePath = formFile.FileName    
  9.     };    
  10.   
  11.     _context.products.Add(pr);    
  12.     await _context.SaveChangesAsync();    
  13.     return Ok();    
  14. }  
I am getting a 415 error in the browser console log
while it was a JPG image that i tried to upload
So i dont really understand it

Answers (3)