微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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_photo

function 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),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');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐