6

I want to show preview of an image before it is uploaded. I have found a partial solution that works for ie6 and firefox, and havent yet tested it in ie7 or ie8. But i want a solution that works in safari, ie7 and ie8 as well. Here is the solution obtained by combining the ie6 and firefox solution:

function preview(what) {
if(jQuery.browser.msie) {
document.getElementById("preview-photo").src=what.value;
return;
}
else if(jQuery.browser.safari) {
document.getElementById("preview-photo").src=what.value;
return;
}
document.getElementById("preview-photo").src=what.files[0].getAsDataURL();
//  alert(jQuery("#preview-photo").height());
//  alert(jQuery("#preview-photo").width());
var h = jQuery("#preview-photo").height();  
var w = jQuery("#preview-photo").width();//assuming width is 68, and height is floating
if ((h > 68) || (w > 68)){
if (h > w){
jQuery("#preview-photo").css("height", "68px");
jQuery("#preview-photo").css("width", "auto");
}else {
jQuery("#preview-photo").css("width", "68px");
jQuery("#preview-photo").css("height", "auto");
}
}
}

The getAsDataURL() part works in firefox, and the "src=what.value" part works in ie6, but what would work in safari, and does "src=what.value" work in ie7 and ie8 as well? If not, is there some solution that also works there? I will be happy if i can make the image preview work in 5 or 6 browsers. If it doesn't then is the only option to have two forms with image upload part of another form?

umar
  • 4,309
  • 9
  • 34
  • 47

5 Answers5

5

You can use the following function. Tested on IE7+ and Firefox and chrome

function loadname(img, previewName){  

var isIE = (navigator.appName=="Microsoft Internet Explorer");  
var path = img.value;  
var ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase();  

 if(ext == "gif" || ext == "jpeg" || ext == "jpg" ||  ext == "png" )  
 {       
    if(isIE) {  
       $('#'+ previewName).attr('src', path);  
    }else{  
       if (img.files[0]) 
        {  
            var reader = new FileReader();  
            reader.onload = function (e) {  
                $('#'+ previewName).attr('src', e.target.result);  
            }
            reader.readAsDataURL(img.files[0]);  
        }  
    }  

 }else{  
  incorrect file type  
 }   
}  

<input type="file" name="image" onchange("loadname(this,'previewimg')") >
<img src="about:blank" name="previewimg" id="previewimg" alt="">
M Rostami
  • 4,035
  • 1
  • 35
  • 39
2

Work in firefox and chrome

<input type="file" id="file" />
<div id="div"></div>
<script type="text/javascript">
function view() {
    var f = document.getElementById("file").files[0];
    var reader = new FileReader();
    reader.onload = (function(evt) {  //evt get all value
        document.getElementById('div').innerHTML = 
            "PIC :<img src=" +
            evt.target.result + "/>" ;
    });
    reader.readAsDataURL(f);
}
</script>
Toto
  • 89,455
  • 62
  • 89
  • 125
asraful009
  • 585
  • 1
  • 6
  • 11
1

Link to the blob as you would link to any image, of course you have to update the src as soon as the images soon to be uploaded is given or changed, here is how I do it, I didn't have the time to test it in Windows Browsers (i.e IE).

This example also implements basic validation: http://jsfiddle.net/J3GP7/

    <style>
        #image_preview {
            display:none;
        }
    </style>

    <form>
        <p>
            <label for="image">Image:</label><br />
            <input type="file" name="image" id="image" />
        </p>
    </form>
    <div id="image_preview">
        <img src="#" /><br />
        <a href="#">Remove</a>
    </div>

    <script>
    /** 
    onchange event handler for the file input field.
    * It emplements very basic validation using the file extension.
    * If the filename passes validation it will show the image 
    using it's blob URL and will hide the input field and show a delete
    button to allow the user to remove the image
    */
    jQuery('#image').on('change', function () {
        ext = jQuery(this).val().split('.').pop().toLowerCase();
        if (jQuery.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            resetFormElement(jQuery(this));
            window.alert('Not an image!');
        } else {
            file = jQuery('#image').prop("files")[0];
            blobURL = window.URL.createObjectURL(file);
            jQuery('#image_preview img').attr('src', blobURL);
            jQuery('#image_preview').slideDown();
            jQuery(this).slideUp();
        }
    });

    /**
    onclick event handler for the delete button.
    It removes the image, clears and unhides the file input field.
    */
    jQuery('#image_preview a').bind('click', function () {
        resetFormElement(jQuery('#image'));
        jQuery('#image').slideDown();
        jQuery(this).parent().slideUp();
        return false;
    });

    /** 
     * Reset form element
     * 
     * @param e jQuery object
     */
    function resetFormElement(e) {
        e.wrap('<form>').closest('form').get(0).reset();
        e.unwrap();
    }
    </script>
Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
1

This will be a serious security issue if done. You can't have a preview of a file in the users computer. You have to upload the file to the server and can show the preview of the file after it is successfully uploaded.

rahul
  • 184,426
  • 49
  • 232
  • 263
0

jquery ajax file upload

$('[name="send"]').click(function(){

   view();

   v_data = {
                news_header : $('[name="news_header"]').val(),
                news_auth : $('[name="news_auth"]').val(),
                news_image : image, //this var taking for view() function what i use before
                news_news : $('[name="news_news"]').val()    

            };

   $("#show").html(v_data.news_Header + " " + v_data.news_auth + " "+ v_data.news_image + " "+ v_data.news_news );

   $.ajax({
        type    :   "POST",
        url     :   './insert_news_data.php',
        enctype: 'multipart/form-data',        
        data    :   v_data,

        success: function(data) {
            alert(data);
        }
   });


});
asraful009
  • 585
  • 1
  • 6
  • 11