Emre Dereli

Emre Dereli

  • NA
  • 9
  • 698

Post Image to Asp.Net Web API from OpenFileDialog

Aug 16 2018 3:40 AM
I want to post image I select from OpenFileDialog to Web API. Then i will read url.
 
Like :
>"https://localhost:1111/api/images/1.jpg"
 
Image:
  1. BitmapImage src = new BitmapImage();  
  2. src.BeginInit();  
  3. src.CacheOption = BitmapCacheOption.OnLoad;  
  4. src.UriSource = new Uri(path);  
  5. src.EndInit();  
  6. productImage.Source = src;  
Button_Click :
  1. private void Button_Click(object sender, RoutedEventArgs e)  
  2. {  
  3. OpenFileDialog fileDialog = new OpenFileDialog();  
  4. fileDialog.Multiselect = false;  
  5. fileDialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";  
  6.   
  7. if(fileDialog.ShowDialog() == true){SendImage(new ImageDTO() { image =fileDialog.FileName });}}  
SendImage():
  1. public bool SendImage(ImageDTO dto)  
  2. {  
  3. string url = "http://localhost:52185/api/StoreImage";  
  4. var wc = new WebClient();  
  5. wc.Headers.Add("Content-Type""application/x-www-form-urlencoded");  
  6. var parameters = new NameValueCollection(){{ "image", dto.image }};  
  7. var res = wc.UploadValues(url, "POST",parameters);  
  8. return true;}  
This line throws :
  1. var res = wc.UploadValues(url, "POST",parameters);  
> System.Net.WebException: 'The remote server returned an error: (500)
> Internal Server Error.'
 
ImageDTO :
  1. public class ImageDTO  
  2. {  
  3. public string image;  
  4. }  
ImagesController.cs :
  1. public class ImagesController :ApiController  
  2. {  
  3. [HttpPost[Route("api/StoreImage")]  
  4. public string StoreImage(ImageDTO request){  
  5. var buffer = Convert.FromBase64String(request.image);  
  6. HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer);  
  7. //Do whatever you want with filename and its binaray data.  
  8. try{  
  9. if (objFile != null && objFile.ContentLength > 0)  
  10. {  
  11. string path = "";objFile.SaveAs(path);  
  12. //Don't Forget to save path to DB  
  13. }  
  14. }  
  15. catch(Exception ex)  
  16. {  
  17.   
  18. }  
  19. return "OK";}}  
It is a WPF application. I have never used Asp.Net Web API. How can i do this?

Answers (1)