Click here to Skip to main content
15,884,078 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I need to upload images using jquery $.ajax and web api controllers

The Model is simple:

public class Person{

  [Required] 
  public string Name {get;set;}

  public HttpPostedFileBase Photo{ get; set; }

}


The api controller is very simple too:

[HttpPost]        
public HttpResponseMessage Save(Person person)
           
  if (!ModelState.IsValid)
  {
     Request.CreateResponse(HttpStatusCode.BadRequest)
  }
  return Request.CreateResponse(HttpStatusCode.OK);
                   
}


What I have tried:

And here is my doubt : How to configure the ajax call?

With "?????" I show where are my doubts. 

<pre>

function SaveImage(){

  var ulr= 'http://localhost:5555/api/Uploader/';

  var person = { 
          Name : 'Donald',
          Photo : ?????       //--->  what hould I assign to photo?
          };

   
$.ajax({
        url: url,
        method: "POST",
        data: person,
        cache: false,
        dataType: ???? ,  //  json ??
        contentType: ????
    }).done(function (res) {
        alert('OK');
    })
    .fail(function (res) {
        alert('PROBLEMS!!');
    })

}


Thanks in advance!!
Pascualito
Posted
Updated 30-May-19 4:40am
Comments
F-ES Sitecore 30-May-19 11:08am    
There are thousands of examples of how to upload images using ajax, please do a google search before posting
Pascualito 13-Jun-19 14:34pm    
I'll take it into account :-)

1 solution

The best way to do this would be to not build your own JSON from scratch; and to use JavaScripts FormData object to assemble the information and submit it.

Thoughbot | Ridiculously simple Ajax uploads with FormData[^]
SitePoint | Easier Ajax With the HTML5 FormData Interface — SitePoint[^]
Stack Overflow | How can retrieve string formdata js in c sharp[^]
 
Share this answer
 
Comments
Pascualito 13-Jun-19 14:49pm    
Thanks for your answer!!
I still wonder if I can addapt the FormData solution to complex javascript objects
, what I mean is, an object which has child objects and is built dynamically

var survey = {
Title : 'one title',
LogoImage : ??
Questions = [{ Text:'one question', Options:[{},{}...,{}] },....,{}]
}

Thanks and greetings!!!
MadMyche 13-Jun-19 17:30pm    
The FormData object has append() and set() methods which allow you to add values to the object. You should be able to use one of these to pass in your JSON object
Pascualito 19-Jun-19 16:13pm    
Thanks MadMyche

I didn't know that. I will experiment with FormData

Greetings!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900