WordPress主题开发中使用Ajax异步更新前端用户头像
html代码如下:
<div class="file"> <span>上传头像</span> <input type="file" name="addPic" class="addPic" style="" id="addPic" accept=".jpg, .gif, .png" resetonclick="true" data-nonce="<?php echo $wp_create_nonce; ?>"></div>//其中<?php $wp_create_nonce = wp_create_nonce('wpshequ-'.get_current_user_id());?>
js(使用了JS中的FormData)代码如下:
<script type="text/javascript"> $("#addPic").change(function(e){ var _this = $(this) var nonce = _this.data("nonce") var file = e.currentTarget.files[0]; console.log(file) //结合formData实现图片预览 var sendData=new FormData(); sendData.append('nonce',nonce); sendData.append('action','update_avatar_photo'); sendData.append('file',file); $.ajax({ url: "/wp-admin/admin-ajax.php", type: 'POST', cache: false, data: sendData, processData: false, contentType: false }).done(function(res) { if (res.status == 1) { layer.msg(res.msg, function(){ location.reload(); }); setTimeout(function(){location.reload()},1000) }else{ layer.msg(res.msg, function(){ location.reload(); }); } }).fail(function(res) { layer.msg('网络错误', function(){ location.reload(); }); }); });</script>//其中的弹窗提示使用了layer.js
php后端处理代码如下:
// 上传头像avatar_photofunction mx_update_avatar_photo(){ header('Content-type:application/json; Charset=utf-8'); global $current_user; $uid = $current_user->ID; $nonce = !empty($_POST['nonce']) ? $_POST['nonce'] : null; $file = !empty($_FILES['file']) ? $_FILES['file'] : null; if ($nonce && !wp_verify_nonce($nonce, 'wpshequ-' . $uid)) { echo json_encode(array('status' => '0', 'msg' => '非法请求'));exit; } $file_index = mb_strrpos($file["name"],'.'); //扩展名定位 //图片验证 $is_img = getimagesize($file["tmp_name"]); if(!$is_img && true){ echo json_encode(array('status' => '0', 'msg' => '上传文件类型错误'));exit; } //图片类型验证 $image_type = ['image/jpg', 'image/gif', 'image/png', 'image/bmp', 'image/pjpeg', "image/jpeg"]; if(!in_array($file['type'], $image_type) && true){ echo json_encode(array('status' => '0', 'msg' => '禁止上传非图片类型文件'));exit; } //图片后缀验证 $postfix = ['.png','.jpg','.jpeg','pjpeg','gif','bmp']; $file_postfix = strtolower(mb_substr($file["name"], $file_index)); if(!in_array($file_postfix, $postfix) && true){ echo json_encode(array('status' => '0', 'msg' => '上传后缀不允许'));exit; } if ( !empty( $file ) ) { // 获取上传目录信息 $wp_upload_dir = wp_upload_dir(); // 将上传的图片文件移动到上传目录 md5纯命名图片 $info = pathinfo($file['name']); $ext = empty($info['extension']) ? '' : '.' . $info['extension']; $name = basename($file['name'], $ext); $basename = time().'-'.substr(md5($name), 0, 15) . $ext; // $filename = $wp_upload_dir['path'] . '/' . $basename; $re = rename( $file['tmp_name'], $filename ); $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . $basename, 'post_mime_type' => $file['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', $basename ), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $filename ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); if($attach_id){ update_user_meta($uid, 'wp_user_avatar', $attach_id); echo json_encode(array('status' => '1', 'msg' => '上传成功'));exit; } else { echo json_encode(array('status' => '0', 'msg' => '上传失败'));exit; } } echo json_encode(array('status' => '0', 'msg' => '文件错误'));exit;}add_action('wp_ajax_mx_update_avatar_photo', 'mx_update_avatar_photo');add_action('wp_ajax_nopriv_mx_update_avatar_photo', 'mx_update_avatar_photo');
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END