【问题标题】:how to preview an image before upload in various browsers如何在各种浏览器中上传之前预览图像
【发布时间】:2010-12-25 15:25:55
【问题描述】:

我想在上传之前显示图像的预览。我找到了适用于 ie6 和 firefox 的部分解决方案,但尚未在 ie7 或 ie8 中对其进行测试。但我想要一个适用于 safari、ie7 和 ie8 的解决方案。下面是结合ie6和firefox方案得到的解决方案:

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

getAsDataURL() 部分在 firefox 中有效,“src=what.value”部分在 ie6 中有效,但什么在 safari 中有效,“src=what.value”在 ie7 和 ie8 中也有效吗?如果没有,是否有一些解决方案也适用于那里?如果我能让图像预览在 5 或 6 个浏览器中工作,我会很高兴。如果没有,那么唯一的选择是让两个表单具有另一个表单的图像上传部分吗?

【问题讨论】:

    标签: html image upload preview


    【解决方案1】:

    链接到blob,就像链接到任何图像一样,当然,一旦给出或更改了即将上传的图像,您必须立即更新 src,这是我的做法,我没有有时间在 Windows 浏览器(即 IE)中测试一下。

    这个示例还实现了基本验证: 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>
    

    【讨论】:

      【解决方案2】:

      jquery ajax 文件上传

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

      【讨论】:

        【解决方案3】:

        在 Firefox 和 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>
        

        【讨论】:

          【解决方案4】:

          你可以使用打击功能。在 IE7+ 和 Firefox 和 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="">
          

          【讨论】:

            【解决方案5】:

            如果这样做,这将是一个严重的安全问题。您无法在用户计算机中预览文件。您必须将文件上传到服务器,并且上传成功后可以显示文件的预览。

            【讨论】:

            • 不正确。新的 HTML5 File API 正是为此目的。它完全保护了文件路径,您必须通过 FileReader 读取所有数据
            • 请注意这个答案是 3 岁。
            猜你喜欢
            • 2011-05-26
            • 1970-01-01
            • 2021-12-27
            • 1970-01-01
            相关资源
            最近更新 更多