`

ie6,ie7,ie8和firefox下兼容的图片上传预览

阅读更多

不需要后台支持,完全在前台通过js完成的

用到了一个jquery插件 image-upload-preview

下载地址:

http://code.google.com/p/image-upload-preview/

 

下面的代码是里面的示例:

 

<html>
<head>
  <title>Image Upload Preview Demo</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <!-- Make sure that we can test against real IE8 -->
  <meta http-equiv="X-UA-Compatible" content="IE=8"/>
  <script src="imageuploadpreview.js"></script>
  <style type="text/css">
    body {
      margin: 20px;
      font: 80% / normal 'arial', 'sans-serif';
    }

    #upload {
      border: solid 3px #ccc;
    }

    .preview-image {
      display: block;
      margin: 10px 0;
      border: solid 3px #aaa;
      padding: 1px;
      background: #fff;
    }
  </style>
</head>
<body>

<h1>Image Upload Preview Demo</h1>

<p>Now's it's only compatible with IE6, IE7, IE8, and Firefox 3</p>

<p>
  <a href="http://code.google.com/p/image-upload-preview/">Google code project
    home
  </a>
</p>

<form>
  <input type="file" id="upload" style="width:400px; padding:3px;"/>
  <div id="file-info"></div>
</form>


<script type="text/javascript">
  (function() {
    var demo = new ImageUploadPreview(
        
        // Upload Input Element
        document.getElementById('upload'),

        // onPreviewSuccess handler.
        function(imgInfo) {
          var info = [];
          for (var i in imgInfo) {
            info.push('<li>', i, ' = ', imgInfo[i], '</li>');
          }

          if (info.length) {
            info.unshift('<ul>');
            info.push('</ul>');
          }
          this.getImageElement().className = 'preview-image';
          document.getElementById('file-info').innerHTML = info.join('');
        },

        // onPreviewFail handler.
        function() {
          this.getImageElement().className = '';
        });

    demo.setMaxImageSize(demo.getInputElement().offsetWidth, 300);


    // If the value already exists, try display image.
    demo.preview();
  })();
</script>
</body>
</html>

 调整file的宽度,就可以调整预览图片的宽度

/**
 * @fileoverview
 * JavaScript Image Upload Preview.
 * Tested and compatible with IE6, IE7, IE8, Firefox 3.
 * 
 * @author Hedger Wang (hedgerwang@gmail.com)
 *
 */

/**
 * @constructor
 * @param {HTMLInputElement|String} input
 * @param {Function?} opt_onSuccess
 * @param {Function?} opt_onFail
 */
function ImageUploadPreview(input, opt_onSuccess, opt_onFail) {
  this.construct(input, opt_onSuccess, opt_onFail);
}

/**
 * Empty image that shows either for Http:// or Https://.
 * @define {String}
 */
ImageUploadPreview.BLANK_IMAGE_SRC = '//www.google.com/images/cleardot.gif';


/**
 * @define {RegExp}
 */
ImageUploadPreview.BASE64_IMG_URL_PATTERN =
/^data:image\/((png)|(gif)|(jpg)|(jpeg)|(bmp));base64/i;


/**
 * @type {HTMLInputElement}
 * @private
 */
ImageUploadPreview.prototype.input_ = null;


/**
 * @type {Function}
 * @private
 */
ImageUploadPreview.prototype.onChangeHandler_ = null;


/**
 * @type {Function}
 * @private
 */
ImageUploadPreview.prototype.onPreviewSuccessHandler_ = null;


/**
 * @type {Function}
 * @private
 */
ImageUploadPreview.prototype.onPreviewFailHandler_ = null;


/**
 * @type {HTMLImageElement}
 * @private
 */
ImageUploadPreview.prototype.image_ = null;


/**
 * @private
 * @type {boolean}
 */
ImageUploadPreview.prototype.isCompatible_ = null;


/**
 * @private
 * @type {Number}
 */
ImageUploadPreview.prototype.maxWidth_ = 200;


/**
 * @private
 * @type {Number}
 */
ImageUploadPreview.prototype.maxHeight_ = 200;


/**
 * @param {HTMLInputElement|String} input
 * @param {Function?} opt_onSuccess
 * @param {Function?} opt_onFail 
 * @public
 */
ImageUploadPreview.prototype.construct =
function(input, opt_onSuccess, opt_onFail) {
  if (typeof input == 'string') {
    input = document.getElementById(input);
  }

  this.onPreviewFailHandler_ = opt_onFail;
  this.onPreviewSuccessHandler_ = opt_onSuccess;
  this.input_ = input;
  this.bindEvents_();
  this.image_ = this.createImage_();
};


/**
 * @public
 */
ImageUploadPreview.prototype.dispose = function() {
  var fn = this.onChangeHandler_;

  // Already disposed.
  if (!fn) return;

  var el = this.input_;

  if (el.addEventListener) {
    el.removeEventListener('change', fn, false);
  } else if (el.attachEvent) {
    el.detachEvent('onchange', fn);
  }

  this.onChangeHandler_ = null;
  this.input_ = null;
  this.image_ = null;
};

/**
 * @public
 */
ImageUploadPreview.prototype.preview = function() {
  var that = this;

  var onLoad = function(imgInfo) {
    // Do thing now, maybe do something later.
    that.maybeCallFunction_(that.onPreviewSuccessHandler_, imgInfo);
  };

  var onError = function(src) {
    if (!tryLoad()) {
      that.showEmptyImage_();
      that.maybeCallFunction_(that.onPreviewFailHandler_, src);
    }
  };

  var loadMethods = [
    this.maybeShowImageWithDataUri_,
    this.maybeShowImageByPath_
  ];

  var tryLoad = function() {
    if (!loadMethods.length) {
      return false;
    }
    var fn = loadMethods.shift();
    fn.call(that, onLoad, onError);
    return true;
  };
  tryLoad();
};


/**
 * @public
 * @return {HTMLImageElement}
 */
ImageUploadPreview.prototype.getImageElement = function() {
  return this.image_;
};


/**
 * @public
 * @return {HTMLInputElement}
 */
ImageUploadPreview.prototype.getInputElement = function() {
  return this.input_;
};


/**
 * @public
 * @param {Number} maxW
 * @param {Number} maxH
 */
ImageUploadPreview.prototype.setMaxImageSize = function(maxW, maxH) {
  this.maxHeight_ = isNaN(maxH) ? 10000 : maxH;
  this.maxWidth_ = isNaN(maxW) ? 10000 : maxW;
};


/**
 * @private
 * @return {HTMLImageElement}
 */
ImageUploadPreview.prototype.createImage_ = function() {
  var doc = this.input_.document || this.input_.ownerDocument;
  var img = doc.createElement('img');
  img.src = ImageUploadPreview.BLANK_IMAGE_SRC;
  img.width = 0;
  img.height = 0;
  this.input_.parentNode.insertBefore(img, this.input_.nextSibling || null);
  return img;
};


/**
 * @private
 */
ImageUploadPreview.prototype.bindEvents_ = function() {
  var that = this;

  var fn = this.onChangeHandler_ = function(e) {
    e = e || window.event;

    if (!e.target && e.srcElement) {
      e.target = e.srcElement;
    }

    that.handleOnchange_.call(that, e);
  };

  var el = this.input_;

  if (el.addEventListener) {
    el.addEventListener('change', fn, false);
  } else if (el.attachEvent) {
    el.attachEvent('onchange', fn);
  }
};


/**
 * @param {Event} e
 * @private
 */
ImageUploadPreview.prototype.handleOnchange_ = function(e) {
  this.preview();
};


/**
 * @private
 */
ImageUploadPreview.prototype.showEmptyImage_ = function() {
  this.showImage_(ImageUploadPreview.BLANK_IMAGE_SRC, 0, 0)
};


/**
 * @private
 * @param {string} src
 * @param {number} w
 * @param {number} h
 */
ImageUploadPreview.prototype.showImage_ = function(src, w, h) {

  if (w > h) {
    if (w > this.maxWidth_) {
      h = h * this.maxWidth_ / w;
      w = this.maxWidth_;
    }
  } else {
    if (h > this.maxHeight_) {
      w = w * this.maxHeight_ / h;
      h = this.maxHeight_;
    }
  }

  var img = this.image_;
  img.src = src;

  var imgStyle = img.style;
  imgStyle.maxHeight = this.maxHeight_ + 'px';
  imgStyle.maxWidth = this.maxWidth_ + 'px';
  imgStyle.width = (w >= 0) ? Math.round(w) + 'px' : 'auto';
  imgStyle.height = (h >= 0) ? Math.round(h) + 'px' : 'auto';
};


/**
 * @param {Function?} fn
 * @param {Object?} var_args
 */
ImageUploadPreview.prototype.maybeCallFunction_ = function(fn, var_args) {
  if (typeof fn != 'function') return;
  var_args = Array.prototype.slice.call(arguments, 1);
  fn.apply(this, var_args);
};


/**
 * Note: Only Firefox 3 can do file.getAsDataURL() by 6/1/2009.
 * See {@link https://developer.mozilla.org/En/NsIDOMFile}.
 * @private
 * @param {Function?} opt_onload
 * @param {Function?} opt_onerror
 */
ImageUploadPreview.prototype.maybeShowImageWithDataUri_ =
function(opt_onload, opt_onerror) {
  var el = this.input_;
  var file = el.files && el.files[0];
  var src;
  var fileName = el.value;

  // Check if we can access the serialized file via getAsDataURL().
  if ((file && file.getAsDataURL) &&
      (src = file.getAsDataURL()) &&
      (ImageUploadPreview.BASE64_IMG_URL_PATTERN.test(src))) {

    var that = this;
    var img = this.image_;


    if ('naturalWidth' in this.image_) {
      // Firefox has naturalWidth.
      this.image_.src = src;

      setTimeout(function() {
        that.showImage_(src, img.naturalWidth, img.naturalHeight);
        that.maybeCallFunction_(opt_onload, {
          width: img.naturalWidth,
          height: img.naturalHeight,
          fileName : fileName,
          fileSize: el.files[0].fileSize
        });
      }, 10);

    } else {
      // Use default CSS max-width / max-height to render the size.
      that.showImage_(src, -1, -1);

      this.maybeCallFunction_(opt_onload, {
        fileName : fileName,
        width: img.offsetWidth,
        height: img.offsetHeight,
        fileSize: el.files[0].fileSize
      });
    }
  } else {
    this.maybeCallFunction_(opt_onerror, fileName);
  }
};


/**
 * Note: IE6 ~ IE8 can access image with local path. By 6/1/2009.
 *       However, this may still not work if the security setting changes.
 * @private
 * @param {Function?} opt_onload
 * @param {Function?} opt_onerror
 */
ImageUploadPreview.prototype.maybeShowImageByPath_ =
function(opt_onload, opt_onerror) {

  var that = this;
  var el = this.input_;
  var img = new Image();
  var timer;
  var fileName = el.value.split(/[\\\/]/ig).pop();

  var dispose = function() {
    if (timer) {
      window.clearInterval(timer);
    }
    img.onload = null;
    img.onerror = null;
    timer = null;
    dispose = null;
    img = null;
    that = null;
    checkIsComplete = null;
    handleError = null;
    handleComplete = null;
  };

  // Handle the case whether the File is not a image file or the path is not a
  // valid path to access.
  var handleError = function() {
    that.maybeCallFunction_(opt_onerror, el.value);
    dispose();
  };

  var handleComplete = function() {
    var w = img.width;
    var h = img.height;
    that.showImage_(img.src, w, h);
    that.maybeCallFunction_(opt_onload, {
      src:fileName,
      width: w,
      height: h,
      fileSize: img.fileSize // Note that FileSize is an IE's only attribute.
    });
    dispose();
  };

  var checkIsComplete = function(e) {
    e = e || window.event;
    var type = e && e.type;

    if (type == 'error') {
      // If the onError event is called.
      handleError();
    } else  if (img.complete || type == 'load') {
      // Sometimes IE does not fire "onload" event if the image was cahced.
      // So we have to check the "complete" state to know whether it's ready.
      if (!img.width || !img.height) {
        // Even it's not a real image, the onload event may still gets fired.
        // Check if its width or height is 0. If true, it's not a real image.
        handleError();
      } else {
        handleComplete();
      }
    }
  };

  img.onload = checkIsComplete;
  img.onerror = checkIsComplete;
  timer = window.setInterval(checkIsComplete, 50);

  // In IE, el.value us the full path of the file rather than just the fileName,
  // and we'd test if we can load image from this path.
  img.src = el.value;

};

 

分享到:
评论

相关推荐

    兼容IE6,IE7,IE8和Firefox的图片上传预览效果

    标题提到的"兼容IE6,IE7,IE8和Firefox的图片上传预览效果"直指浏览器兼容性问题,这是一个在过去很长一段时间内困扰开发者的关键挑战。由于早期的Internet Explorer(IE6, IE7, IE8)对现代Web标准的支持不足,而...

    JS图片预览(兼容IE6、IE7、IE8和FF)

    在JavaScript(简称JS)中实现图片预览,尤其是在兼容老版本的Internet Explorer(如IE6、IE7、IE8)以及Firefox(FF)等浏览器上,需要考虑多种技术策略和兼容性问题。下面我们将详细讨论如何实现这个功能,并着重...

    IE6,Ie7,ie8 ,和火狐下的图片上传预览 解决方案

    针对“IE6, IE7, IE8, 和火狐下的图片上传预览解决方案”这一主题,我们将深入探讨如何在这些浏览器中实现一致的图片上传预览功能。 首先,IE6、IE7和IE8是微软Internet Explorer的早期版本,它们对于现代Web标准的...

    上传图片预览-兼容IE6,IE7,IE8,FF

    标题中的“上传图片预览-兼容IE6,IE7,IE8,FF”指的是一个Web开发的技术解决方案,目的是实现图片上传前的预览功能,并确保该功能在早期版本的Internet Explorer(IE6、IE7、IE8)以及Firefox浏览器上都能正常工作...

    图片上传预览 兼容ie6 ,ie7 ,火狐3.0

    虽然可以在ie6,ie7,火狐预览、但在谷歌浏览器还是不行、哪位高人要是有更好的办法浏览、能否交流交流. qq:253930407 email:ruanjingwang@yahoo.com.cn

    图片上传 预览 兼容 IE firefox

    本篇文章将详细探讨如何实现“图片上传预览”功能,并确保在IE 6/7/8及Firefox(包括新版)等浏览器中的兼容性。 首先,我们需要了解不同浏览器对HTML5新特性的支持情况。现代浏览器如Chrome、Safari和新版Firefox...

    兼容ie6、ie7、ie8 和FF的本地上传图片预览

    标题中提到的“兼容ie6、ie7、ie8 和FF的本地上传图片预览”主要涉及以下技术点: 1. **FileReader API**:这是一个HTML5的新特性,用于读取文件。在支持的浏览器中,可以通过`FileReader.readAsDataURL(file)`方法...

    2014-5-6更新 兼容ie[6-9]、火狐、Chrome、opera、maxthon3、360浏览器的js本地图片预览

    兼容ie[6-9]、火狐、Chrome、opera、maxthon3、360浏览器的js本地图片预览"提供了一个JavaScript解决方案,用于实现一个功能强大的本地图片预览功能,它能在多种主流浏览器中正常工作,包括古老的Internet Explorer ...

    jQuery上传图片预览,简洁版,可兼容IE和FIREFOX

    本文将深入探讨如何使用jQuery实现一个简洁版的图片上传预览功能,这个功能可以兼容包括IE和Firefox在内的多种浏览器。 首先,我们需要理解图片预览的基本原理。在用户选择文件之前,我们无法直接预览图片。但是,...

    asp.net 多图片上传 可预览 兼容火狐 IE

    可预览 兼容火狐 IE"是一个功能实现,它允许用户在网页上一次性上传多张图片,并在上传前或上传过程中提供预览功能,同时确保该功能在不同浏览器,如火狐(Firefox)和IE(Internet Explorer)之间具有良好的兼容性...

    js预览图片 上传前预览图片 兼容ie6.7.8.9 ff 谷歌 opera 苹果浏览器不兼容

    上传前预览图片 兼容ie6.7.8.9 ff 谷歌 opera 苹果浏览器",表明这是一个旨在解决浏览器兼容性问题的解决方案,涵盖了老版本的Internet Explorer(IE6到IE9)以及Firefox、Chrome、Opera和Safari等主流浏览器。...

    图片预览(支持IE7)

    不过,值得注意的是,“不兼容FF”表明这种方法只适用于IE7,并不适用于Firefox浏览器。Firefox支持更标准的CSS和JavaScript,所以如果要实现跨浏览器的图片预览,需要采用不同的策略,如使用JavaScript库(如jQuery...

    asp 上传图片预览 ie7-11 火狐 谷歌 qq 360

    在ASP(Active Server Pages)开发中,实现图片上传并预览功能是一项常见的需求,尤其在兼容多种浏览器,如IE7到IE11、火狐、谷歌、QQ浏览器和360浏览器时,需要考虑跨浏览器的兼容性问题。本文将详细讲解如何在这些...

    JavaScript预览上传,支持IE7、IE8、火狐浏览器

    JavaScript解决预览上传问题,目前支持IE7、IE8、火狐浏览器; 上网查找了大量资料,然而能用的代码却寥寥无几;竟然弄出来了,就共享给大家。

    兼容IE火狐图片预览功能

    我找了很久,大多数都不能兼容最新版的火狐,这个能行,希望可以帮助到真正需要的人

    在线预览PDF(无需任何插件) 支持IE/Firefox/Coogle

    6. **浏览器兼容性**:针对IE、Firefox和Chrome等不同浏览器,可能需要针对其特性进行特定的代码优化和适配。例如,对于IE,可能需要使用条件注释或polyfill来兼容旧版本的JavaScript API。 7. **响应式设计**:...

    JS实现单图片预览,兼容IE、火狐

    本文将深入探讨如何使用纯JS实现这一功能,同时确保兼容性覆盖到古老的Internet Explorer(IE)和Firefox浏览器。我们首先需要了解的是,浏览器对文件API的支持程度不同,特别是对于IE,我们需要采用一些特殊的技术...

    asp.net IE6、7、8 图片上传前预览

    在ASP.NET环境中,针对Internet Explorer 6、7和8这三个早期版本实现图片上传前的预览...综上所述,要实现在ASP.NET中IE6、7、8浏览器上的图片上传预览,需要利用JavaScript和特定的IE滤镜技术,并确保兼容性和安全性。

Global site tag (gtag.js) - Google Analytics