2009-12-11 5 views
6

Quiero mostrar vista previa de la imagen antes de que sea subido. He encontrado una solución parcial que trabaja para IE6 y Firefox, y no he probado todavía en IE7 o IE8. Pero quiero una solución que funcione en safari, ie7 y ie8 también. Aquí está la solución obtenida mediante la combinación de la solución IE6 y Firefox:cómo una vista previa de una imagen antes de subida en varios navegadores

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"); 
} 
} 
} 

La parte getAsDataURL() funciona en Firefox, y el "src = what.value" parte funciona en IE6, pero lo que sería trabajar en Safari, y ¿funciona "src = what.value" en ie7 y ie8 también? Si no, ¿hay alguna solución que también funcione allí? Estaré contento si puedo hacer que la vista previa de la imagen funcione en 5 o 6 navegadores. Si no es así, ¿entonces la única opción es tener dos formularios con carga de imagen de otra forma?

Respuesta

1

Este será un problema de seguridad grave si se hace. No puede tener una vista previa de un archivo en la computadora de los usuarios. Debe cargar el archivo en el servidor y puede mostrar la vista previa del archivo una vez que se haya cargado correctamente.

+3

No es cierto. La nueva API de archivos HTML5 sirve exactamente para este propósito. Se protege totalmente la ruta del archivo, y usted tiene que leer todos los datos a través de un FileReader –

+1

Nota esta respuesta es de 3 años de edad. – Ash

5

puede utilizar la función de golpe. probado en IE7 + y Firefox y 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=""> 
+0

esto funciona muy bien. debe marcarse como la respuesta. – JT703

+0

no funciona ... ¿puedes agregar violín? –

+0

No funciona en IE7 –

2

trabajo en Firefox y 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> 
0

archivo ajax jquery cargar

$('[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); 
     } 
    }); 


}); 
0

Enlace a la blob como se puede enlazar a cualquier imagen, de por supuesto, usted tiene que actualizar el src tan pronto como las imágenes que pronto será subido es dada o cambiado, aquí es cómo lo hago, no tienen el tiempo para probarlo en Windows Navegadores (es decir, iE).

Este ejemplo también implementa la validación básica: 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> 
Cuestiones relacionadas