第一步:引入jquery文件和jaxFileUpload文件
文件位置:https://pan.baidu.com/s/1jHEyIyy
第二步,前端:
<div class="form-group"> <label class="col-xs-12 col-sm-3 col-md-2 control-label"><span class="text-danger"></span> 用户头像</label> <div class="col-sm-9 col-xs-12"> <input type="file" name="avatar" id="avatar" value=""/> <input type="hidden" name="avatar_name" id="avatar_name" value=""/> </div> </div> <div class="form-group" id="img_form_group" style="<?php if(!$member_common['avatar']){echo 'display:none';}?>"> <label class="col-xs-12 col-sm-3 col-md-2 control-label"><span class="text-danger"></span> </label> <div class="col-sm-9 col-xs-12"> <img width="100px;" <?php echo $member_common['avatar']?'src="/data/upload/member_avatar/'.$member_common['avatar'].'"':'';?> /> </div> </div>
function ajaxFileUpload() { $.ajaxFileUpload ( { url:'/index.php/admin/member/memberAjax?do=upload_avatar', secureuri:false, fileElementId:'avatar', dataType: 'json', success: function (data, status) { if(data.code !=1){ layer.msg(data.msg); }else{ $('input[name="avatar_name"]').val(data.data.avatar_name); $("#img_form_group").find('img').attr('src',data.data.avatar_url); $("#img_form_group").show(); } $('input[name="avatar"]').bind('change',uploadChange); }, error: function (data, status, e) { layer.msg('上传失败'); $('input[name="avatar"]').bind('change',uploadChange); } } ) } function uploadChange(){ var filepatd=$("#avatar").val(); var extStart=filepatd.lastIndexOf("."); var ext=filepatd.substring(extStart,filepatd.length).toUpperCase(); if(ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){ layer.msg("文件格式错误"); $("#avatar").attr('value',''); return false; } if ($("#avatar").val() == '') return false; ajaxFileUpload(); } $(function(){ $('#avatar').change(function(){uploadChange()}); })
第三步,ci框架后端:
case 'upload_avatar': if (is_uploaded_file($_FILES['avatar']['tmp_name'])) { try{ $img_arr = imgUpload( array( 'path' => FCPATH . 'data/upload/member_avatar', 'field' => 'avatar', 'pre' => 'avatar_', ) ); $file_name=$img_arr[0]['file_name']; $file_name = (string) $file_name; if(!is_file(FCPATH.DATA_UPLOAD.'member_avatar/'.$file_name)){ throw new Exception("上传失败"); } $data=array(); $data['avatar_name']=$file_name; $data['avatar_url']=getMemberAvatar($file_name); $this->output(1,'上传成功', $data); }catch(Exception $e){ $error_msg=$e->getMessage(); $error_msg=str_replace('<p>','',$error_msg); $error_msg=str_replace('</p>','',$error_msg); $this->output(400,$error_msg); } }else{ $this->output(400,"请选择上传的图片"); } break;
第四步:
错误处理:http://blog.csdn.net/imlinjunjie/article/details/49403199