码迷,mamicode.com
首页 > Web开发 > 详细

带预览的图片上传(相当于手写的)

时间:2017-10-30 15:00:45      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:null   array   photo   highlight   路径   ref   sub   style   think   

一.HTML

<form id="subheadphoto" action="{:U(‘user/center/avatar‘)}" method="post" enctype="multipart/form-data">
        <div class="pb_left fl user_pic">
          <img src="{:sp_get_user_avatar_url($user[‘avatar‘])}"  onclick="$(‘#change_pic‘).click()" width="112" height="112" />
        </div>
        <input type="file" name="headphoto" id="change_pic" style="display: none;" onchange="getPhoto(this)"/>
</form>

 

 

二.js

<script type="text/javascript">
     //头像上传
        var imgurl = "";
         function getPhoto(node) {
        try{
            var file = null;
            if(node.files && node.files[0] ){
                file = node.files[0];
            }else if(node.files && node.files.item(0)) {
                file = node.files.item(0);
            }
            //Firefox 因安全性问题已无法直接通过input[file].value 获取完整的文件路径
            try{
                imgURL =  file.getAsDataURL();
            }catch(e){
                imgRUL = window.URL.createObjectURL(file);
            }
        }catch(e){
            if (node.files && node.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    imgURL = e.target.result;
                };
                reader.readAsDataURL(node.files[0]);
            }
        }
        creatImg(imgRUL);
        return imgURL;
    }

    function creatImg(imgRUL){
        var textHtml = "<img  src=‘"+imgRUL+"‘width=‘112‘ height=‘112‘/>";
        $(".user_pic").html(textHtml);
    }

    $(function(){
          $("#change_pic").change(function(){
            $("#subheadphoto").submit();
          });
    })
</script>

三.php(此处用为thinkphp的方法为例)

// 用户头像编辑
    public function avatar(){
    $uid=$this->userid;
        $upload = new \Think\Upload();
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array(‘jpg‘, ‘gif‘, ‘png‘, ‘jpeg‘);// 设置附件上传类型
        $upload->rootPath  =      ‘data/Upload/avatar/‘; // 设置附件上传根目录
        // 上传单个文件 
        $info   =   $upload->uploadOne($_FILES[‘headphoto‘]);//文件获取方式
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
            $avatar_path=$info[‘savepath‘].$info[‘savename‘];
            $data[‘avatar‘]=$avatar_path;
            if($this->users_model->where("id=‘$uid‘")->save($data)!==false){
            $this->redirect(‘center/safe‘);
            }
        }
    }

 

带预览的图片上传(相当于手写的)

标签:null   array   photo   highlight   路径   ref   sub   style   think   

原文地址:http://www.cnblogs.com/wjw-/p/7753708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!