js 上传图片
效果:
html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>js上传文件</title> <link rel="stylesheet" href="css/test2.css"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> //图片类型验证 function verificationPicFile(file) { var fileTypes = [".jpg", ".png"]; var filePath = file.value; //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false if (filePath) { var isNext = false; var fileEnd = filePath.substring(filePath.indexOf(".")); for (var i = 0; i < fileTypes.length; i++) { if (fileTypes[i] == fileEnd) { isNext = true; break; } } if (!isNext) { alert('不接受此文件类型'); file.value = ""; return false; } } else { return false; } var fileSize = 0; var limitSize = 259; var fileMaxSize = limitSize * 1024; //图片大小 var filePic = file.files[0]; if (filePath) { fileSize = filePic.size / 1024; var size = fileSize; console.log('fileSize', fileSize); console.log('filePath', filePath); if (size > fileMaxSize) { alert("文件大小不能大于200!"); file.value = ""; return false; } else if (size <= 0) { alert("文件大小不能为0M!"); file.value = ""; return false; } var reader = new FileReader(); reader.onload = function(e) { var data = e.target.result; //加载图片获取图片真实宽度和高度 var image = new Image(); image.onload = function() { var width = image.width; var height = image.height; console.log('width', width); console.log('height', height); if (width < 300 | height < 300) { alert("文件尺寸符合!"); var upLoad = $('#upLoad'); upLoad.attr('src', data); } else { alert("文件尺寸应为:300*300!"); file.value = ""; return false; } }; image.src = data; }; reader.readAsDataURL(filePic); } else { return false; } } </script> </head> <body> <a href="javascript:;" class="file">选择文件 <input type="file" name="" id="" onchange="verificationPicFile(this)"> </a> <img id="upLoad" src="" alt=""> </body> </html>
1.css:
.file { position: relative; display: inline-block; background: #D0EEFF; border: 1px solid #99D3F5; border-radius: 4px; padding: 4px 12px; overflow: hidden; color: #1E88C7; text-decoration: none; text-indent: 0; line-height: 20px; } .file input { position: absolute; font-size: 100px; right: 0; top: 0; opacity: 0; } .file:hover { background: #AADFFD; border-color: #78C3F3; color: #004974; text-decoration: none; }