废话不多说,直接上代码:
<body>
<input type="file" name="file" class="fileBtn" onchange="showPreview(this)" onmouseover="showImg()" onmouseout="hideImg()"/>
<span class="btn-text" id="pic">选择图片</span>
<div class="view-box" id="viewBox">
<img id="preview" width=300/>
</div>
<script type="text/javascript">
function showPreview(source){
var file = source.files[0];
if(!file){
alert('请先上传图片');
}
if (file.type == "image/jpeg" || file.type == "image/png") {
if(window.FileReader){
var fr = new FileReader();
fr.onloadend = function(e){
var img = new Image();
img.src=e.target.result;
imgWidth = img.width;
imgHeight = img.height;
imgSize = file.size;
if(judgeImg(imgWidth,imgHeight,imgSize)){ //检测图片尺寸
document.getElementById('pic').innerHTML=file.name;
document.getElementById('preview').src=e.target.result;
doUploadFile(file,imgWidth, imgHeight, imgSize)//与服务器交互
};
}
fr.readAsDataURL(file);
}
}else{
alert('文件格式有误');
}
}
function judgeImg(imgWidth,imgHeight,imgSize){
if(imgWidth>1000){alert('这里对图片宽度进行限定');return;}
if(imgHeight>1000){alert('这里对图片高度进行限定');return;}
if(imgSize>500*1024){alert('这里对图片尺寸进行限定');return;}
return true;
}
function doUploadFile(file,width, height, fileSize){
var form = new FormData();
form.append("fileName", file.name); // 可以增加表单数据
form.append("fileSize", file.size); // 可以增加表单数据
form.append("file", file);
var req = new XMLHttpRequest();
req.open("post", imgUrl);
req.send(form);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
var data = JSON.parse(req.responseText);
if (data.errorCode == 0) {
//上传图片成功
} else {
//上传图片失败
}
}
};
}
function showImg(){
if(document.getElementById('preview').src){
document.getElementById('viewBox').style.opacity=1;
}
}
function hideImg(){
document.getElementById('viewBox').style.opacity=0;
}
</script>
<style>
.fileBtn{
opacity:0;
position:relative;
z-index:999;
cursor:pointer }
.btn-text{
position:relative;
color:green;
left:-200px;
}
.view-box{
width:300px;
border:solid 3px #ccc;
opacity:0;
}
</style>
</body>