不依托第三方插件实现的php原生上传图片的方法,操作步骤如下。
1、在当前主题或者当前插件的目录下,创建新文件script/upload.js,写入代码
点击复制代码 ActionScript
!function(o){
var b=$('body');
function upload(){
var id='ajax_upload'+new Date().getTime(),d = $(this);;
b.append(`<input type="file" id="${id}" accept="${o.accept}" style="display:none">`);
var el=$('#'+id);
b.one('change','#'+id,function(){
var f = new FormData();
f.append('file',$(this)[0].files[0]);
$.ajax({
url: ajaxurl+o.src,
type: 'POST',
dataType: 'json',
data: f,
contentType: false,
processData: false,
xhr: function() {
var xhr = new XMLHttpRequest(),t;
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
t = Math.floor(e.loaded / e.total * 100);
o.progress && o.progress(d, t);
}
});
return xhr;
},
success:function(r){
o.success(d, r);
},
error:function(r){
o.error && o.error(d,r);
}
});
}),
el.click();
}
b.on('click',o.click,upload);
}({
src: 'zb_ai_xzjt', //这里AppName改为你的应用ID
click: '.zb_upimgbutton',
accept: '.jpg,.jpeg,.png,.gif,.bmp,.svg',
success: function(e, r){
console.log('上传成功,图片链接:'+r.url);
e.siblings('.zb_input_img').attr("value", r.url);
e.siblings('img').attr('src',r.url);
e.val('选择文件');
},
error: function(e){
alert('上传失败');
},
progress: function(e,n){
e.val('上传进度:'+n+'%');
}
});
2、通过Filter_Plugin_Cmd_Ajax添加ajax异步上传
点击复制代码 PHP
function ActivePlugin_zb_ai_xzjt() {
Add_Filter_Plugin('Filter_Plugin_Cmd_Ajax', 'zb_ai_xzjt_Cmd_Ajax');
}
function zb_ai_xzjt_Cmd_Ajax($src)
{
global $zbp;
if ($src == 'zb_ai_xzjt') {
if (!$zbp->CheckRights('UploadPst')) {
$zbp->ShowError(6);
}
Add_Filter_Plugin('Filter_Plugin_Upload_SaveFile', 'zb_ai_xzjt_Upload_SaveFile_Ajax');
$_POST['auto_rename'] = 1;
PostUpload();
echo json_encode(array('url' => $GLOBALS['tmp_ul']->Url));
exit;
}
}
function zb_ai_xzjt_Upload_SaveFile_Ajax($tmp, $ul)
{
$GLOBALS['tmp_ul'] = $ul;
}
3、在需要的地方调用,比如在文章编辑页面。
点击复制代码 PHP
function ActivePlugin_zb_ai_xzjt() {
Add_Filter_Plugin('Filter_Plugin_Edit_Response5','zb_ai_xzjt_edit_response');
}
function zb_ai_xzjt_edit_response() {
global $zbp, $article;
echo '<script type="text/javascript" src="' . $zbp->host . 'zb_users/plugin/zb_ai_xzjt/script/upload.js"></script>';
echo '<style type="text/css">
.zb_input_img{width:40%!important;}
.zb_upimgbutton{ width:120px;}
.zb_upimg{width:100px;vertical-align: middle;}</style>';
echo '<div id="tesetu">缩略图1:
<input name="meta_pic" id="edtTitle" type="text" class="zb_input_img" value="' . $article->Metas->tesetu1 . '" />
<input type="button" class="zb_upimgbutton" value="选择图片">
<img class="zb_upimg" src="' . $article->Metas->pic. '">
</div>';
echo '<div id="tesetu">缩略图2:
<input name="meta_pic2" id="edtTitle" type="text" class="zb_input_img" value="' . $article->Metas->tesetu2 . '" />
<input type="button" class="zb_upimgbutton" value="选择图片">
<img class="zb_upimg" src="' . $article->Metas->pic2. '">
</div>';
}