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);
}
});
}