zblog主题、插件用js上传文件
利用此代码帮助你在开发应用时快速实现图片上传功能,别再傻乎乎的依赖UE编辑器的上传功能了(好像在说我曾经的自己^_^)
js代码
!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: 'AppName_upload', //这里AppName改为你的应用ID
click: '.upimgbutton', //这里改成你上传按钮的css选择器
accept: '.jpg,.jpeg,.png,.gif,.bmp,.svg',
success: function(e, r){
console.log('上传成功,图片链接:'+r.url);
e.siblings('.input_img').attr("value", r.url); //把链接填写在上传按钮兄弟元素的 .input_img文本框
e.siblings('img').attr('src',r.url); //修改同级元素img图片链接
e.val('选择文件'); //恢复上传按钮名称
},
error: function(e){
alert('上传失败');
},
progress: function(e,n){
e.val('上传进度:'+n+'%');
}
});
php代码
//把下面的AppName都改为你的应用ID
Add_Filter_Plugin('Filter_Plugin_Cmd_Ajax','AppName_Cmd_Ajax'); //挂载接口
function AppName_Cmd_Ajax($src){
global $zbp;
if ($src == 'AppName_upload'){
if (!$zbp->CheckRights('UploadPst')) {
$zbp->ShowError(6);
}
Add_Filter_Plugin('Filter_Plugin_Upload_SaveFile','AppName_Upload_SaveFile_Ajax');
$_POST['auto_rename'] = 1;
PostUpload();
echo json_encode(array('url' => $GLOBALS['tmp_ul']->Url));
exit;
}
}
function AppName_Upload_SaveFile_Ajax($tmp, $ul){
$GLOBALS['tmp_ul'] = $ul;
}