1.单张图片预览
html元素
<img width="100" height="100" id="allUrl" src="<%=path%>${brand.imgUrl}"/>
<input id="uploadFileId" type="file" name="pic" onchange="previewPic()"/>
js
function previewPic(){
var uploadFile = document.getElementById("uploadFileId");
var previewImg = document.getElementById("allUrl");
// 设置预览
if(uploadFile.files && uploadFile.files[0]){
previewImg.style.display = "block";
previewImg.src = window.URL.createObjectURL(uploadFile.files[0]);
}
}
2.多张图片预览(multiple="multiple",遍历上传时的每张图片文件,生成图片url,再在一个容器中添加多个img标签)
html
<input id="uploadPicId" type="file" οnchange="uploadPic()" name="pics" multiple="multiple"/>
function uploadPic(){
var uploadFile = document.getElementById("uploadPicId"); // 上传文件元素
if(uploadFile.files){ // 上传文件存在
// 遍历所有上传文件,并生成对应的img标签
var html = '<tr>';
for(var i=0;i<uploadFile.files.length;i++){
var picUrl = window.URL.createObjectURL(uploadFile.files[i]);
html += '<td><img height="150" width="200" style="block" src="';
html += picUrl;
html += '"/></td>';
}
html += '</tr>';
// 将所有img标签添加到容器中,用于展示
$("#tab_2").append(html);
}
}
3.其它图片预览方法:
1.HTML样式
<div id='divId'>
<img id='imgId'/>
</div>
<input type='file' onChange=previewImage(this,'divId','imgId')/>
2.Javascript
//图片预览功能
//file 上传文件对象
//包裹图片的div编号
//imgId 预览图片id
function previewImage(file,divId,imgId)
{
var MAXWIDTH = 200;
var MAXHEIGHT = 200;
var div = document.getElementById(divId);
if (file.files && file.files[0])
{
div.innerHTML ='<img id='+imgId+'>';
var img = document.getElementById(imgId);
img.onload = function(){
var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginTop = rect.top+'px';
}
var reader = new FileReader();
reader.onload = function(evt){img.src = evt.target.result;}
reader.readAsDataURL(file.files[0]);
}
}
function clacImgZoomParam( 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;
}