以下为完整代码,jQuery库需自行下载加载
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Gao-Robert</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="renderer" content="webkit">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
</head>
<body>
<img id="avatar" width="200" height="200" src="./res/img/profileEdit/upload.png" alt="">
<input id='chooseImage' type="file">
</body>
</html>
<!-- 加载jQuery库 -->
<script src="./res/static/js/jq.js"></script>
<script>
//上传图片
$('#chooseImage').on('change', function () {//当chooseImage的值改变时,执行此函数
var filePath = $(this).val(), //获取到input的value,里面是文件的路径
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(), //获取文件类型
size = this.files[0].size / 1024 // 获取文件大小
src = window.URL.createObjectURL(this.files[0]); //转成可以在本地预览的格式
//检查图片宽高
if (this.files && this.files[0]) {
var img = new Image();
img.onload = function () {
var width = img.width;
var height = img.height;
// 检查是否是图片
if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
alert('上传错误,文件格式必须为:png/jpg/jpeg');
return;
} else if (false) {// 检查是否是图片大小
alert('图片大小不能大于5M');
return;
}
else if (width < 200 || height < 200) {// 检查图片尺寸
alert('图片尺寸需大于200*200')
}
else { // 都通过则可以预览图片
$('#avatar').attr('src', src);
}
};
img.onerror = function () {
alert("error!");
};
img.src = window.URL.createObjectURL(this.files[0]);
}
});
</script>
复制代码