利用FormData实现附件上传(实现上传图片显示)

坚强是说给别人听的谎言 提交于 2020-03-15 18:14:47
<script type="text/javascript">
            function  creatXMLHttpRequest(){
                    var obj =null;
                                if(window.ActiveObject){
                                        obj = new ActiveObject("Microsoft.XMLHTTP");
                                }else{
                                        obj = new XMLHttpRequest();
                                }
                            return obj;
                }
    
            window.onload=function(){
                fileinfo=document.getElementById('myheads').files[0];
            }
            function uploaded(){
                    var xhr = creatXMLHttpRequest();
                    var fd = new FormData();
                    fd.append('myheads',fileinfo);
                    xhr.onreadystatechange=function(){
                            if(xhr.readyState==4 && xhr.status ==200){
                                    alert(xhr.responseText);
                            }
                    }
                    xhr.open('post','jsonupload.php');
                    xhr.send(fd);
            }
 </script> 

                <input type="file" id='myheads' name="myhead"  value="wenjian"/>
                <input type="button"  value="上传" onclick="uploaded();"/>
 </body>


上图为fileinfo的内容

立即显示被上传图片效果

            window.onload=function(){
                fileinfo=document.getElementById('myheads').files[0];
            //    console.log(fileinfo);
            }

            function uploaded(){
                    var xhr = creatXMLHttpRequest();
                    var fd = new FormData();
                    fd.append('myheads',fileinfo);
                    document.getElementById('img').src=window.URL.createObjectURL(fileinfo);
                    xhr.onreadystatechange=function(){
                            if(xhr.readyState==4 && xhr.status ==200){
                                    alert(xhr.responseText);
                            }
                    }
                    xhr.open('post','jsonupload.php');
                    xhr.send(fd);
            }

总结:HTML5新特性FormData

可以通过:

fileinfo=document.getElementById('myheads').files[0];来捕获客户端上传文件的信息

将需要上传的文件信息载入到FormData对象内部

fd.append('finfo',fileinfo);

然后通过 window.URL.createObjectURL(fileinfo);文件的url地址信息,二进制编码存在


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!