1

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.

2
  • 2
    Have you watched the request / response in the browser's console? Do a var_dump($_FILES), which is where the image would be. Commented May 16, 2016 at 19:24
  • 1
    If a file was uploaded, you can find the information in $_FILES, not $_POST. Commented May 16, 2016 at 19:26

1 Answer 1

3

Use print_r($_FILES) to check if any file was sent and not $_POST.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.