8👍
✅
Ok, I can’t exactly explain why, but it seems like var formData = new FormData($(this));
is not enough alone, it needs to be explicitly appended, because reasons? If anyone can explain, please do.
The working code:
<form action="http://localhost:8000/accounts/api/image/"
method="put"
enctype="multipart/form-data">
<input name="image" type="file" id="image">
<input type="submit">
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$('form').submit(function(e) {
var formData = new FormData($(this)[0]);
formData.append('image', $('#image')[0].files[0]);
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: formData,
headers: {'Authorization': 'Token mytoken'},
cache: false,
contentType: false,
processData: false,
success: function() { alert('it works') },
});
e.preventDefault();
});
</script>
Source:stackexchange.com