How to preview an image before and after upload?
Asked Answered
T

5

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?

Tobacconist answered 25/4, 2013 at 6:8 Comment(2)
possible duplicate of Preview an image before it is uploadedSnowfall
This is the simple method https://mcmap.net/q/478280/-how-to-preview-an-image-before-and-after-uploadVigilant
L
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>

Lifelong answered 25/4, 2013 at 6:13 Comment(3)
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'>?Tobacconist
@meVeekay, can we set maximum number of image in your above solution ?Maud
am using multiple input, how can it be done with above codeBertha
B
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");
    }
});
Banausic answered 4/6, 2015 at 11:18 Comment(0)
V
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>
Vigilant answered 23/4, 2020 at 6:48 Comment(0)
B
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
     }
?>
Bennet answered 25/4, 2013 at 6:43 Comment(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.Tobacconist
R
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" />
Roderic answered 6/6, 2019 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.