600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 原生JS实现异步图片上传(预览)

原生JS实现异步图片上传(预览)

时间:2019-02-19 03:58:56

相关推荐

原生JS实现异步图片上传(预览)

效果

实现过程分为两步

1. 用户点击添加后通过 H5文件读取 FileReader对象以DataURL的格式读取图片

2. 通过FormData对象生成表单数据,通过ajax上传到后台

HTML

<style>.file-box{display: inline-block;position: relative;padding: 3px 5px;overflow: hidden;color:#fff;background-color: #ccc;}.file-btn{position: absolute;width: 100%;height: 100%;top: 0;left: 0;outline: none;background-color: transparent;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;}.prev-box{display: inline-block; min-width: 200px;min-height: 120px;border-radius: 5px;padding: 5px;border:1px #ccc dotted;}</style><body><form id="form1"><div class="file-box"><input type="file" class="file-btn" onChange="uploadImg(this)" accept="image/*" name="image"/>上传文件</div><br><div class="prev-box" id="prev-box"><img style="width: 200px;" id="img"></div><div id="uploadMsg" style="color: #f00"></div></form></body>

JS

function uploadImg(obj){//1. 图片预览//如果浏览器不支持 FileReader 则用文字提示if(typeof FileReader == 'undefined'){var prevBox = document.getElementById('prev-box')prevBox.innerHTML = "浏览器不支持预览"}else{//获取上传文件,返回 File对象var file = obj.files[0];var reader = new FileReader()//注册读取成功的回调函数reader.onload = function (e) {var img = document.getElementById("img");img.src = e.target.result;}//开始以 DataURL格式读取文件 reader.readAsDataURL(file)}//2. 图片上传if(typeof FormData == 'undefined'){alert('浏览器不支持图片上传')}else{var form = document.getElementById('form1')var data = new FormData(form)//添加自定义字段data.append("CustomField", "This is some extra data")//ajax请求var httpRequest = new XMLHttpRequest();httpRequest.open("POST", "upload.php", true);httpRequest.onload = function(oEvent) {if (httpRequest.status == 200) {//服务器返回的保存路径console.log(httpRequest.responseText)} else {document.getElementById('uploadMsg').innerHTML = '图片上传失败,错误码:' + httpRequest.status}};httpRequest.send(data);}}

相关知识

1. 通过获取 <input type="file" /> 的files获取结果为 File对象的伪数组集合

2. FileReader 支持输出多个格式 readAsDataURL( ) 、readAsText( ) 、readAsArrayBuffer( ),他们都接收一个 File 或者 Blob 对象作为参数

3.FileReader 对象支持多个事件回调 onloadstart( ) --开始读取、onprogress( ) --正在读取、onabort( ) --读取中断、onload( ) -- 读取成功,读取成功后数组保存在事件对象中e.target.result

4. FromData 对象可以单独创建,也可以通过Form创建,使用append添加字段

5.如果FormData对象是通过表单创建的,则表单中指定的请求方式会被应用到方法open()中。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。