js点击头像,上传新头像

来源:互联网 发布:布鲁克林法学院 知乎 编辑:程序博客网 时间:2024/05/20 22:40

应用场景:(点击头像选择新图片,并上传)


html:<em style="width: 60px;display: block;position: absolute;"><input type="file" style="opacity:0; filter:alpha(opacity=0); height: 60px; width: 60px; position: absolute; top: 0; left: 0; z-index: 9;" onchange="handleFiles(this,'icon')"><img src="{$headimgurl}" style="height: 60px; width: 60px;" id="icon"></em>
js:<script>function handleFiles(obj,id) {    file = document.getElementById("icon");    var files = obj.files;    img = new Image();    if(window.URL){        //File API        img.src = window.URL.createObjectURL(files[0]); //创建一个object URL,并不是你的本地路径        img.onload = function(e) {        window.URL.revokeObjectURL(this.src); //图片加载后,释放object URL        }    }    file.src=img.src;    //上传文件        var fd = new FormData(),//实例化一个表单        xhr = new XMLHttpRequest();        fd.append('headimg', files[0]);//追加图片元素        xhr.open('post', 'user.php?act=act_edit_img');//请求方式,请求地址        xhr.send(fd);}</script>

后台接收并、上传图片

原创粉丝点击