<!DOCTYPE html>
<html>
<head>
<title>JavaScript校验图片格式及大小</title>
<script type="text/javascript">
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(target,id) {
var fileSize = 0;// 图片大小
var filetypes =[".jpg",".png"];// 图片类型
var filepath = target.value;// 图片路径
var filemaxsize = 1024*10;// 图片最大10M
if(filepath){
var isnext = false;
var fileend = filepath.substring(filepath.indexOf("."));
if(filetypes && filetypes.length>0){
for(var i =0; i<filetypes.length;i++){
if(filetypes[i]==fileend){
isnext = true;
break;
}
}
}
if(!isnext){
alert("不接受此图片类型");
target.value ="";
return false;
}
}else{
return false;
}
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
if(!fileSystem.FileExists(filePath)){
alert("图片不存在,请重新输入");
return false;
}
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024;
if(size > filemaxsize){
alert("图片大小不能超过10M");
target.value ="";
return false;
}
if(size<=0){
alert("图片大小不能为0M");
target.value ="";
return false;
}
// 上传图片到服务器
var path = '/img/year/';
$.ajaxFileUpload({
url:'${contextPath}/do/file/uploadFile/?path='+path,
secureuri:false,
fileElementId:'fileuploade',
dataType: 'json',
success: function (data, status){
var path = data.path;
var imgHost = data.imgHost;
$("#img_file").css("display","block");
$("#tempimg").attr("src",imgHost+path);
$("#add_img_url").val(path);
},
error: function (data, status, e){
$.messager.alert('操作提示', '上传失败!');
}
});
}
</script>
</head>
<body>
<input type="file" id="fileuploade" name="file_path" onchange="fileChange(this);">
</body>