Im trying to send file to api using ajax , but form-data always null in both cases mentioned below
<form id="myformdoc">
<input type="file" size="45" name="file" id="file">
</form>
<script>
$('#file').on("change", function () {
// var formdata = new FormData($('form').get(0));
let myForm = document.getElementById('myformdoc');
let formData = new FormData(myForm);
$.ajax({
url: url,
type: 'POST',
data: formdata ,
cache: false,
processData: false,
contentType: false,
success: function (color) {
;
},
error: function () {
alert('Error occured');
}
});
});
</script>
Any idea why form-data always null ?
2
Answers
Try adding
multipart/form-data
in contentType parameter.You need to use
formData append to add files to your
formData
function.Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.
If you have other inputs in your
form
you canappend
them as well if you like to.Demo: