html5上传图片
Posted Rella
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html5上传图片相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> <style> .upload-wrapper { font-size: 0; } .file-input { position: relative; display: inline-block; width: 200px; height: 50px; line-height: 50px; border-radius: 5px; text-align: center; font-size: 18px; font-weight: bold; background-color: #009688; color: #fff; vertical-align: top; z-index: 1; } #upload{ position: absolute; left: 0; top: 0; width: 200px; height: 50px; opacity: 0; } #upload-img { display: inline-block; margin-left: 30px; height: 200px; } .upload-pic { height: 100%; width: auto; } </style> </head> <body> <div class="upload-wrapper"> <span class="file-input">上 传<input type="file" id="upload" /></span> <div id="upload-img"></div> </div> <script> var input = document.getElementById(‘upload‘); if(typeof FileReader === undefined) { input.setAttribute(‘disabled‘,‘disabled‘); }else { input.addEventListener(‘change‘,readFile,false); } function readFile(){ var file = this.files[0]; if(!/image\/\w+/.test(file.type)) { alert("请选择图片!"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { var data = this.result.split(‘,‘); var tp = (file.type == ‘image/png‘) ? ‘png‘ : ‘jpg‘; var targetDiv = document.getElementById(‘upload-img‘); var uploadPic = document.getElementsByClassName(‘upload-pic‘); if(uploadPic.length === 0) { var img = document.createElement(‘img‘); img.src = data[0]+‘,‘+data[1]; img.className = ‘upload-pic‘; targetDiv.appendChild(img); } else { uploadPic[0].src = data[0]+‘,‘+data[1]; } //之后的处理将图片数据上传到服务器 } } </script> </body> </html>
以上是关于html5上传图片的主要内容,如果未能解决你的问题,请参考以下文章
HTML5可预览多图片ajax上传(使用formData传递数据)