29

I am going to preview an image or photo in a form, but it doesn't work and the HTML code looks like this as below:

<form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm">
    <p><label for="image">Upload Image:</label>
    <input type="file" id="imageUpload"/></p>
    <p><button type="submit" class="button">Save</button></p>
        <div id="preview">
            <img width="160px" height="120px" src="profile pic.jpg" id="thumb" />
        </div>
    </form>

and incorporated JS code/script below:

<script type="text/jaavascript">
$(document).ready(function(){
    var thumb=$('#thumb');
    new AjaxUpload('imageUpload',{
    action:$('newHotnessForm').attr('action'),
    name:'image',
    onSubmit:function(file,extension){
        $('#preview').addClass('loading');
    },
    onComplete:function(file,response){
        thumb.load(function(){
            $('#preview').removeClass('loading');
            thumb.unbind();
        });
        thumb.attr('src',response);
    }
    });
});

There are 2 main questions on my form:
1. Why doesn't the preview of the image or picture work?
2. How to paste the photo from the form when the save button is clicked, it will go/link to another PHP or PHP page that I created?

2

5 Answers 5

84

Try this: (For Preview)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

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

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

3
  • 1
    Your solution is really work,but is it will work where the pic or image that I uploaded that link to another page under the code like <form id="form1" runat="server" action='page.php'>?
    – JCChan
    Apr 25, 2013 at 6:34
  • @meVeekay, can we set maximum number of image in your above solution ? Nov 4, 2017 at 21:49
  • am using multiple input, how can it be done with above code May 7, 2018 at 12:15
8

meVeekay's answer was good and am just making it more improvised by doing 2 things.

  1. Check whether browser supports HTML5 FileReader() or not.

  2. Allow only image file to be upload by checking its extension.

HTML :

<div id="wrapper">
    <input id="fileUpload" type="file" />
    <br />
    <div id="image-holder"></div>
</div> 

jQuery :

$("#fileUpload").on('change', function () {

    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();

    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
        if (typeof (FileReader) != "undefined") {

            var image_holder = $("#image-holder");
            image_holder.empty();

            var reader = new FileReader();
            reader.onload = function (e) {
                $("<img />", {
                    "src": e.target.result,
                        "class": "thumb-image"
                }).appendTo(image_holder);

            }
            image_holder.show();
            reader.readAsDataURL($(this)[0].files[0]);
        } else {
            alert("This browser does not support FileReader.");
        }
    } else {
        alert("Pls select only images");
    }
});
6

On input type=file add an event onchange="preview()"

For the function preview() type:

thumb.src=URL.createObjectURL(event.target.files[0]);

Live example:

function preview() {
   thumb.src=URL.createObjectURL(event.target.files[0]);
}
<form>
    <input type="file" onchange="preview()">
    <img id="thumb" src="" width="150px"/>
</form>

2
                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>
1
  • This is not really work on nextimg page,the image didn't displayed and previewed.Is it involved any database?if not,of course, my project is trend to run at client-server.
    – JCChan
    Apr 29, 2013 at 15:36
0

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

    reader.onload = function(e) {
      $('#ImdID').attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);
  }
}
img {
  max-width: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' onchange="readURL(this);" />
<img id="ImdID" src="" alt="Image" />

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.