Search code examples
phphtmlmysqlimagepreview

how to create image uploader with preview


I want to have a form, with multiple parts.

The first part would be images, multiple file upload with a preview of the images before actually uploading them.

The second part has various text form fields.

I have the second part built fine and working, using PHP and MySQL, and the image upload is working too. But I don't know how to show a preview of the images before submitting the form.

EDIT:

using code form an answer:

     <input type='file' onchange="readURL(this);" />
     <img id="blah" src="#" alt="your image" />

with:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

works great, but it only shows 1 thumbnail. I want to create an image thumbnail dynamically for each file.

I'm trying :

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
          var container = $('#previews');
          var image = $('<img>').attr('src', e.target.result).width(150);
          image.appendTo(container);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

with:

    <input type='file' name="files[]" onchange="readURL(this);" multiple />
    <div id="previews"></div>

which works, but how do I loop it for each file inputted?


Solution

  • Take a look at that:

    http://jsbin.com/uboqu3/1/edit

    from this post on stackoverflow: Preview an image before it is uploaded

    Lucian