一.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‘); ???????????} ???????} ???}
带预览的图片上传(相当于手写的)
原文地址:http://www.cnblogs.com/wjw-/p/7753708.html