Gigaxel Gigaxel - 8 months ago 39
Ajax Question

Upload image immediately after selected in file dialog AJAX and PHP

I am making a web app that allows a user to enter certain information and to select an image from his computer and whenever he selects his image and presses ok that image should be immediately uploaded.

<p>Upload image: <input type="file" name="imageToUpload" id="image" accept="image/*" /></p>

So the image should be uploaded whevener you press ok in the File Dialog.
I did everything but this. I want to save the image in a folder called "images" on my server. And I want to save the names of the images to my database so I can recall them later on.
How is this accomplished through AJAX and PHP and how can I check the format of that image so the user can't upload another file instead of the image ?

Answer Source

First of all you have to set an event listener on your image element. I 'll give you an example in native javascript, because it is times faster than jQuery and the payload of using a javascript framework (if you 're not using it anyway) is too heavy. Compare hundreds of kilobytes of the jQuery Framework with 5kB of a native solution.

Here we go:

<input type="file" name="imageToUpload" id="image" accept="image/*">
    var fileNode = document.querySelector('#image'),
        form = new FormData(),
        xhr = new XMLHttpRequest();

    fileNode.addEventListener('change', function( event ) {

        var files = this.files;
        for (var i = 0, numFiles = files.length; i < numFiles; i++) {
            var file = files[i];

            // check mime
            if (['image/png', 'image/jpg'].indexOf(file.type) == -1) {
                // mime type error handling

            form.append('my-files[]', file,;

            xhr.onload = function() {
                if (xhr.status === 200) {
                    // do sth with the response

  'POST', 'upload.php');

What I 've done here? In short: I 'm working with javascript native FormData API and XHR Object wich works in all modern browsers for the latest three major versions. Next we place an event listener on our file node, so the change event is triggered every time the user selects a file. With the File API we get our files and loop through all of them. You can execute several checks on the mime type and the size here. If the file is valid upload it with the xhr Object.

Your upload.php file should do all the security checks again. Check the mime type, the size and the error member in the $_FILES array. In the example the files are stored in $_FILES['my-files'].

If you want drag 'n drop support and a progress bar, just have a look at this example I 've written a few days ago. just have a look at the source code of the site.