js解决file上传图片+图片预览
demo案例中代码为js原生控制,可以根据项目的需求修改为jquery操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="file" id="photo">
<div id="click" style="width: 200px; height: 200px; border: 1px solid #000;"></div>
<script>
document.getElementById('photo').addEventListener('change',function(e){
var files = this.files;
var img = new Image();
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function(e){
var mb = (e.total/1024)/1024;
if(mb>= 2){
alert('文件大小大于2M');
return;
}
img.src = this.result;
img.style.width = "80%";
document.getElementById('click').style.width="200px";
document.getElementById('click').style.height="200px";
document.getElementById('click').innerHTML = '';
document.getElementById('click').appendChild(img);
}
});
</script>
</body>
</html>
前段时间修改bug 再次找到一个不错的方法:
<img alt="" src="${notice.url}" style="width:80px;" id="file_view">
<input type="file" class="filestyle" name="url" id="file_pic"/>
//下面用于图片上传预览功能
function setImagePreview(objc) {
var docObj=document.getElementById(objc.file);
var imgObjPreview=document.getElementById(objc.pic);
if(docObj.files &&docObj.files[0]){
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = objc.width;
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
return true;
} else {
return false;
};
};
$("#file_pic").on("change",function(){
// 使用图片预览控件, opts 配置对象
var opts = {
file : 'file_pic',
pic : 'file_view',
width : '80px'
}
setImagePreview(opts);
})