在Web端開發圖片上傳功能時,往往需要在上傳圖片之前對圖片進行預覽,既可以防止上傳錯誤的圖片,又可以大大提升用戶體驗,但是在IE瀏覽器上為了提升安全性是不支持上傳前預覽的,所以需要使用濾鏡來實現:
<!-- html代碼,不考慮CSS樣式 -->
<img id="preview" alt="" />
<form class="am-form" method="post" enctype="multipart/form-data">
<input type="file" id="head" name="head" onchange="previewImage(this)">
<button type="submit" class="am-btn am-btn-primary am-btn-xs">保存</button>
</form>
下面是js的實現:
// 上傳圖片前預覽
function previewImage(file) {
var MAXWIDTH = 120; // 最大圖片寬度
var MAXHEIGHT = 120; // 最大圖片高度
if (file.files && file.files[0]) {
var img = document.getElementById('preview');
img.onload = function () {
var rect = getZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
}
var reader = new FileReader();
reader.onload = function (evt) {
img.src = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
} else {
//兼容IE
file.select();
var src = document.selection.createRange().text;
var img = document.getElementById('preview');
img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
}
}
// 獲取縮放的尺寸
function getZoomParam(maxWidth, maxHeight, width, height) {
var param = { top: 0, left: 0, width: width, height: height };
if (width > maxWidth || height > maxHeight) {
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if (rateWidth > rateHeight) {
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
} else {
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}
經過測試,在chrome和firefox以及edge瀏覽器上是好用的,IE瀏覽器未進行測試。