2

I have several fields in an HTML form including a file field which I'd like to use to upload images. The problem I am facing is that the API is expecting the form-data in its entirety to be encoded as JSON - how can this format accomodate an image as a binary file?

Here is what I'm looking at so far:

<form method="POST" name="myForm" onsubmit="uploadPost()">
    Name:<input type="text" id="name">
    Location:<input type="text" id="location">
    Image: <input id="image_file" name="image_file[]" type="file" />
    <input type="submit" value="upload">
</form>
function uploadPost(){
    var uName = $("#name").val();
    var uLoc = $("#location").val();
    var apiUrl="https://example.com/upload";
    var image_file = $('#image_file').get(0).files[0];
    var formData = new FormData();
    formData.append("image_file", image_file);
    $.ajax({
        type: "POST",
        url: apiUrl,
        data: 
        {
            name: email,
            location: password,
            image: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
        },
            dataType: "json", 
            success: function(data){
                alert(data.message.image);
            }
    });
}
Emissary
  • 9,954
  • 8
  • 54
  • 65
Sam
  • 115
  • 1
  • 2
  • 6
  • Welcome to SO. I don't see in your `data` definition where you include the information from `image_file[]` or your variable `image_file`. – Twisty Apr 27 '15 at 14:29
  • When you perform the post, do you encounter an error? What is returned? – Twisty Apr 27 '15 at 14:30
  • Is there any other solution to upload image file on json api? – Sam Apr 27 '15 at 14:31
  • it return Uncaught TypeError: Illegal invocation and when I am alerting the file variable then it alert Object File. – Sam Apr 27 '15 at 14:31
  • First, I suspect you saw this very similar post: http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload Which version of JQuery are you using and what version browser are you expecting? – Twisty Apr 27 '15 at 14:38
  • ok thanks. I am going to see it. – Sam Apr 27 '15 at 14:40

0 Answers0