网上找到的一段代码,经过一番测试修改,兼容了IE7+、火狐、谷歌。
并且扩展了多尺寸预览功能,可完美搭配 jquery.Jcrop 插件进行图像裁剪。

插件代码

(function($) {
jQuery.fn.extend({
uploadPreview: function(opts) {
opts = jQuery.extend({
width: null,
height: null,
imgDiv: "#imgDiv",
anyTarget: null,
maxSize: 300,
imgType: ["gif", "jpeg", "jpg", "bmp", "png"],
callback: function() { return false; }
}, opts || {});
var _this = $(this);
var imgDiv = $(opts.imgDiv);
opts.width && imgDiv.width(opts.width);
opts.height && imgDiv.height(opts.height);
var isIE = navigator.appName == 'Microsoft Internet Explorer',
brVersion = navigator.appVersion, version;
isIE && (version = brVersion.split(';')[1].replace(/MSIE[ ]/g,'').replace('.0',''));
handle = function() {
var img = imgDiv.find('img');
opts.anyTarget && $.each(opts.anyTarget.split(','), function(index, val) {
$(val).html(img.clone());
});
img.width(opts.width).height(opts.height);
opts.callback(img);
},
createImg = function(){
imgDiv.html('');
var img = $("<img />");
imgDiv.append(img);
return img;
},
_this.change(function() {
if (this.value) {
if (!RegExp("\.(" + opts.imgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
alert("图片类型必须是" + opts.imgType.join(",") + "中的一种");
this.value = "";
return false;
}
if (isIE &amp;&amp; version < 10) {
if (version == 6) {
var image = new Image();
image.onload = function(){
if( (image.fileSize/1024) > opts.maxSize) {
alert('图片大小不能超过'+opts.maxSize+'K');
return false;
}
}
image.src = 'file:///' + this.value;
createImg().attr('src', image.src);
handle();
} else {
var img = document.selection.createRange().text || $(this).val();
var image = $('<img />')
image.load(function(){
if( (image.fileSize/1024) > opts.maxSize) {
alert('图片大小不能超过'+opts.maxSize+'K');
return false;
}
});
image.attr('src', img);
imgDiv.html('');
image.css({ filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='"+img+"')" });
imgDiv.append(image);
setTimeout(handle, 100);
}
}
else {
var img;
try{
var file = null;
var size = 0;
if(this.files &amp;&amp; this.files[0] ){
file = this.files[0];
size = file.size;
}else if(this.files &amp;&amp; this.files.item(0)) {
file = this.files.item(0);
size = file.fileSize;
}
if((size/1024) > opts.maxSize){
alert('图片大小不能超过'+opts.maxSize+'K');
return false;
}
img = createImg();
//Firefox 因安全性问题已无法直接通过input[file].value 获取完整的文件路径
try{
//Firefox7.0 以下
img.attr('src', file.getAsDataURL());
}catch(e){
//Firefox8.0以上
img.attr('src', window.URL.createObjectURL(file));
}
img.css({ "vertical-align": "middle" });
setTimeout(handle, 100);
}catch(e){
//支持html5的浏览器,比如高版本的firefox、chrome、ie10
if (this.files &amp;&amp; this.files[0]) {
if((this.files[0].size/1024) > opts.maxSize){
alert('图片大小不能超过'+opts.maxSize+'K');
return false;
}
var reader = new FileReader();
reader.onload = function (e) {
imgDiv.attr('src', e.target.result);
};
reader.readAsDataURL(this.files[0]);
setTimeout(handle, 100);
}
};
}
}
});
}
});
})(jQuery);

参数

  • width: 图片容器宽度;
  • height: 图片容器高度;
  • imgDiv: 图片预览容器;
  • anyTarget: 其他关联容器,多个容器逗号隔开;
  • maxSize: 图片大小限制,单位KB;
  • imgType: 图片类型限制;
  • callback: 预览成功后的回调,参数 img(预览的图片节点,jquery类型)。

实例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>图片上传预览</title>
<link href="http://cdn.bootcss.com/jquery-jcrop/0.9.12/css/jquery.Jcrop.css" rel="stylesheet">
<style type="text/css">
.fl {
float: left;
}
.fr {
float: right;
}
.logo-wrap {
overflow: hidden;
margin: 30px 0;
}
.logo-350, .logo-350 img {
width: 350px;
height: 350px;
}
.logo-350 {
margin-right: 30px;
}
.logo-200, .logo-200 img {
width: 200px;
height: 200px;
}
.logo-200 {
margin-bottom: 30px;
}
.logo-200-wrap {
width: 200px;
}
.logo-100, .logo-100 img {
width: 100px;
height: 100px;
}
.logo-60, .logo-60 img {
width: 60px;
height: 60px;
}
.logo-350, .logo-200, .logo-100, .logo-60, .qrcode {
border: 1px solid #ddd;
overflow: hidden;
}
</style>
</head>
<body>
<input type="file" value="上传文件" id="file">
<div class="logo-wrap">
<div class="fl logo-350"></div>
<div class="fl logo-200-wrap">
<div class="logo-200"><div class="content"></div></div>
<div>
<div class="fl logo-100"><div class="content"></div></div>
<div class="fr logo-60"><div class="content"></div></div>
</div>
</div>
</div>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ysdn-wordpress.stor.sinaapp.com/js/jquery.uploadPreview.js"></script>
<script src="http://cdn.bootcss.com/jquery-jcrop/0.9.12/js/jquery.Jcrop.min.js"></script>
<script>
//<![CDATA[
$("#file").uploadPreview({
width: 350,
height: 350,
imgDiv: '.logo-350',
anyTarget: '.logo-200 .content, .logo-100 .content, .logo-60 .content',
maxSize: 1024 * 2,
callback: function(el) {
var jOption = {
setSelect: [75, 75, 275, 275],
minSize: [200, 200],
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1
};
var isIE = navigator.appName == 'Microsoft Internet Explorer',
brVersion = navigator.appVersion, version;
isIE &amp;&amp; (version = brVersion.split(';')[1].replace(/MSIE[ ]/g,'').replace('.0',''));
if (isIE &amp;&amp; version < 10) {
var api = $.Jcrop(el.selector, jOption);
} else {
el.Jcrop(jOption);
}
}
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
$('.logo-200, .logo-100, .logo-60').each(function(index, el) {
var box = $(el), content = box.find('.content'), img = content.find('img');
content.width($('.logo-350').outerWidth()).height($('.logo-350').outerHeight());
var rx = box.width() / c.w;
var ry = box.height() / c.h;
img.css({
width: Math.round(rx * 350) + 'px',
height: Math.round(ry * 350) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
});
}
}
//]]>
</script>
</html>