I am making a image upload system that simply uploads the image as soon as it is attached to the input[type='file'] element. However, I am having difficulties in getting the image to the server side.
Test case
HTML:
<a class="button" data-action="upload-images">Upload Image</a>
<div style="display:none;">
<form method="POST" enctype="multipart/form-data" class="image-upload-form">
<input type="file" name="image" data-caller="upload-images" accept="image/*" />
<input type="hidden" name="object_id" value="1"/>
</form>
</div>
JavaScript:
// Let a custom button open the file selection frame
jQuery( document ).on( "click", "[data-action='upload-images']", function() {
jQuery( this ).parent().find( "[data-caller='upload-images']" ).click();
});
// Catch a file upload
jQuery( document ).on( "change", "[data-caller='upload-images']", function() {
jQuery.ajax({
url: "ajax/image-upload",
type: "POST",
data: new FormData( this.parentNode ),
contentType: false,
processData: false,
success: function( data ) {
console.log( data );
}
});
});
PHP: ajax/image-upload
var_dump($_POST);
Testing
Executing this code gives the following output in the console:
array(1) {
["object_id"]=>
string(1) "1"
} // No image?
The request payload is:
------WebKitFormBoundaryi8mRsBbBQSmCgZ4f
Content-Disposition: form-data; name="image"; filename="TrueTone.png"
Content-Type: image/png
------WebKitFormBoundaryi8mRsBbBQSmCgZ4f
Content-Disposition: form-data; name="object_id"
1
------WebKitFormBoundaryi8mRsBbBQSmCgZ4f--
What I have tried
I really can't find a way to get the uploaded image to the server side. So far I have seen a couple of tutorials that use the same method but catch the file upload onSubmit and use e.preventDefault to cancel the actual submission.
I completely rewrote my code with a submit button to copy this way of catching the image, without any success.
The request payload indicates that the file is being uploaded but it is not visible on the server side. I hope you can help me.
var_dump($_FILES), which is where the image would be.$_FILES, not$_POST.