缘由
之前我的图片是放在用oneindex搭建的网盘上,blog文章的图片存放在Onedrive上,同步至oneindex,但似乎OneDrive的api接口对访问量有限制,有时我浏览博客的会发现图片不能显示。这样的情况持续了很久,直到我偶然了解到了 Chevereto ,于是决定搭建一个图床来存放图片。前段时间我把我博客文章的图片一张一张从OneDrive上转移到了Chevereto图床,虽然我的图片不算太多,但这种在图床页面上传再回到博客文章编辑页面的方式浪费了我很多时间,并且以后更新文章也会使用图床,我可不想这样一步步傻傻地操作。在Chevereto的仪表发现了API V1后,我开始研究。网上关于这个的资料很少,作为一个小白,我的探索之路很是艰辛。
先上一张成果图:
tip:支持多张图片上传哦!
获取API KEY
准备一个Chevereto搭建的图床(废话!),不会搭建的话请Google
登录,转到仪表盘-设置-API
,将API v1 key
记录下来,一会儿要用
API后端设置
进入Chevereto的安装目录,将app/routes/route.api.php
文件拷贝到app/routes/overrides/route.api.php
文件
允许跨域
打开app/routes/overrides/route.api.php
,第二行(<?php
后面)添加如下几行
header('Access-Control-Allow-Origin: https://spiritx.xyz');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, Origin, Accept');
记得把白名单https://spiritx.xyz
改成自己的域名或者改成*
设置API user(可选)
在app/routes/overrides/route.api.php
中,找到$uploaded_id = CHV\Image::uploadToWebsite($source);
那一行,更改为
$uploaded_id = CHV\Image::uploadToWebsite($source,spirit);
将spirit
替换为图床中的用户
前端添加上传按钮(media button)
将以下代码添加到WordPress正在使用的主题目录的functions.php
中
//添加图床上传按钮
add_action('media_buttons', 'add_my_media_button');
function add_my_media_button() {
$currentUser = wp_get_current_user();
if(!empty($currentUser->roles) && in_array('administrator', $currentUser->roles)){
$DOMAIN="图床的域名";
$APIkey="图床的API v1 key";// 是管理员
}
else
return 0; // 非管理员
echo '
<input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>
<label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i> 上传图片到Chevereto</label>
';
?>
<style type="text/css">
#up_to_chevereto {
display: none;
}
#up_img_label {
color: #fff;
background-color: #16a085;
border-radius: 5px;
display: inline-block;
padding: 5.2px;
}
</style>
<script type="text/javascript">
jQuery('#up_to_chevereto').change(function() {
window.wpActiveEditor = null;
for (var i = 0; i < this.files.length; i++) {
var f=this.files[i];
var formData=new FormData();
formData.append('source',f);
jQuery.ajax({
async:true,
crossDomain:true,
url:'https://<?php echo $DOMAIN; ?>/api/1/upload/?key=<?php echo $APIkey; ?>&format=json',
type : 'POST',
processData : false,
contentType : false,
data:formData,
beforeSend: function (xhr) {
jQuery('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');
},
success:function(res){
wp.media.editor.insert('<a href="'+res.image.url+'"><img src="'+res.image.url+'" alt="'+res.image.title+'"></img></a>');
jQuery("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');
},
error: function (){
jQuery("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');
}
});
}
});
</script>
<?php
}
style里的样式可以根据自己偏好自定义
使用预览
这里我的编辑器用的是WP Editor.md,界面不同但不影响上传按钮的使用
2019年12月16日更新
有几个小伙伴反馈说上传有问题,了解情况后主要是https混用和CORS的问题,故在这里更新上传方法,上传方式改用WordPress REST API,为了保证兼容,请确保WordPress版本为4.9+。注意:前文的操作均不用管,以下的操作均在 functions.php
中完成。
注册路由
add_action('rest_api_init', function () {
register_rest_route('chevereto/v1', '/image/upload', array(
'methods' => 'POST',
'callback' => 'upload_to_chevereto',
));
});
之后,可以使用post的方式发送数据到 http(s)://博客域名/chevereto/v1/image/upload 来上传图片。
加入回调函数
function upload_to_chevereto() {
//Authentication
if (!check_ajax_referer('wp_rest', '_wpnonce', false)) {
$output = array('status' => 403,
'message' => 'Unauthorized client.',
'link' => $link,
);
$result = new WP_REST_Response($output, 403);
$result->set_headers(array('Content-Type' => 'application/json'));
return $result;
}
$image = file_get_contents($_FILES["chevereto_img_file"]["tmp_name"]);
$upload_url = '图床的域名/api/1/upload';
$args = array(
'body' => array(
'source' => base64_encode($image),
'key' => '图床的API v1 key',
),
);
$response = wp_remote_post($upload_url, $args);
$reply = json_decode($response["body"]);
if ($reply->status_txt == 'OK' && $reply->status_code == 200) {
$status = 200;
$message = "success";
$link = $reply->image->image->url;
} else {
$status = $reply->status_code;
$message = $reply->error->message;
$link = $link;
}
$output = array(
'status' => $status,
'message' => $message,
'link' => $link,
);
$result = new WP_REST_Response($output, $status);
$result->set_headers(array('Content-Type' => 'application/json'));
return $result;
}
将图床的域名和图床的API v1 key填写完整,注意加上http或https
后台编辑器添加按钮
//添加图床上传按钮
add_action('media_buttons', 'add_my_media_button');
function add_my_media_button() {
echo '
<input id="up_to_chevereto" type="file" accept="image/*" multiple="multiple"/>
<label for="up_to_chevereto" id="up_img_label"><i class="fa fa-picture-o" aria-hidden="true"></i> 上传图片到Chevereto</label>
';
?>
<style type="text/css">
#up_to_chevereto {
display: none;
}
#up_img_label {
color: #fff;
background-color: #16a085;
border-radius: 5px;
display: inline-block;
padding: 5.2px;
}
</style>
<script type="text/javascript">
jQuery('#up_to_chevereto').change(function() {
window.wpActiveEditor = null;
for (var i = 0; i < this.files.length; i++) {
var f=this.files[i];
var formData=new FormData();
formData.append('chevereto_img_file',f);
jQuery.ajax({
async:true,
crossDomain:true,
url:'<?php echo rest_url("chevereto/v1/image/upload") ."?_wpnonce=". wp_create_nonce("wp_rest"); ?>',
type : 'POST',
processData : false,
contentType : false,
data:formData,
beforeSend: function () {
jQuery('#up_img_label').html('<i class="fa fa-spinner rotating" aria-hidden="true"></i> Uploading...');
},
success:function(res){
if (res.status == 200) {
wp.media.editor.insert('<a href="'+res.link+'"><img src="'+res.link+'" alt="'+f.name+'"></img></a>');
jQuery("#up_img_label").html('<i class="fa fa-check" aria-hidden="true"></i> 上传成功,继续上传');
}else{
console.log("code: "+res.status+"message: "+res.message);
}
},
error: function (){
jQuery("#up_img_label").html('<i class="fa fa-times" aria-hidden="true"></i> 上传失败,重新上传');
}
});
}
});
</script>
<?php
}
然后就开始使用吧 ^_^
Comments | 76 条评论
大佬 提示上传失败 不知道咋回事?

@hero 可以看看控制台的报错是什么
@Spirit

提示这个哥
@hero 看着是CORS,你确定设置图床后端允许跨域了吗?
@Spirit 是不是这段就是允许跨越的代码哥?我就是按照这个来的?
header(‘Access-Control-Allow-Origin: https://spiritx.xyz’);
header(‘Access-Control-Allow-Methods: POST’);
header(‘Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, Origin, Accept’);
如果不是要在哪里修改允许跨越,还希望大哥指点一下。
@hero 是这一段没错,注意把 https://spiritx.xyz 改为你的blog域名,此外,看截图你的这个页面存在http、https混用的情况,建议安装插件修复下:SSL Insecure Content Fixer
@Spirit 哥 就是修改了我自己的域名 改成* 这个也不行 这是奇了怪了 has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
@Spirit 哥 域名我改的图床域名 但是图床用了外部存储 应该跟外部存储的这个域名地址应该没关系吧
@hero 不应该改为图床的域名,应该改为blog的域名。不过你写
*
也没用的话说明可能不是这的问题。你登入图床看看图片有没有传上去,如果显示传上去的话,你再试试不用php加header的方法,改用Nginx add_header(如果你用的是Nginx的话),下面是配置文件@Spirit 我说错了哥 是博客的域名
我用的是bt apache
也去了图床看了一下 并没有上传成功
@hero 那可能是https混用,你先检查博客和图床的https状态,确保正常配置了ssl,然后在wp后台安装我说的那个插件,再试试能否上传,如果不行,再另想办法
@hero 假如是博客ssl问题 那我可以把博客的ssl去掉么哥?去掉博客的ssl该如何配置?
@Spirit 按照大佬的指导 也用插件修复ssl 又重新搬了一个新的vps上面去 测试后还是不行 真的是好奇怪好奇怪。。。。
@hero 改了之后还有
Mixed Content
的报错吗该评论为私密评论
@hero 该评论为私密评论
大佬,我安装的5.3wp(4.4的也试了),Chevereto free 本身上传也没问题,第三方插件“Chevereto Uploader by Your-Pictionary.com”也能用。但是按照大佬的教程却一直上传失败,看评论其他人也能用,更觉得郁闷了。试了好久都不行,大佬能给些建议吗?需要检查下哪里。谢谢。
@jinsong 后端有没有修改为允许跨域,我觉得可能是CORS,F12看看控制台有无报错
@Spirit 感谢大佬,允许跨域的域名填成图床的域名了…
@Spirit 大佬,我反代了图床,上传没有问题,但是编辑器中 res.image.url还是图床的域名,怎么才能生成反代域名的路径?
@jinsong 相关代码改成
res.image.url.replace("图床域名","反代路由域名")
@Spirit 感谢大佬为小白解惑,有反代好太多了。
WordPress升级最新版以后,上传不能用了!不知道是需要修改哪里可以重新支持!
@chwl wp 5.0 之后后台默认使用Gutenberg编辑器,目前我还没详细看相关文档,如要采用本文的方法的话可以安装 Classic Editor 返回旧版编辑器,或者和我一样使用 WP Editor.md 编辑器,这样按钮就会出来了
@Spirit 我昨天升级了5.3,升级之前是可以用的,升级之后选择照片以后就没反应了,图床也没上传也没提示!不知道是不是升级哪里出问题了!我用的也是WP Editor.md 编辑器
@chwl 知道问题了,是因为wp 5.3不再暴露jQuery的
$
函数,详情 https://wordpress.org/support/topic/jquery-error-in-custom-theme-after-upgrading-to-5-3/ ,文章代码已经更新,请重新覆盖原有代码@Spirit 谢谢大佬,现在可以上传了!
有点6,要不给Sakura也搞一个
@Mashiro 我觉得OK
, 不过要自己修改Chevereto对使用者来说有点麻烦~
该评论为私密评论
@ソ初ヲ https://codepen.io/tholman/full/jWmZxZ/
感谢。另外API变量上下有出入,复制代码的 时候修改下。
@test 已修改变量名,感谢提醒
test,代码高亮
为什么提交评论后,文章的代码高亮灭了……
@后宫学长 还真是,之前都没发现
,晚上回去修bug 
踩坑好评,同款WP Editor.md好评。

@后宫学长 欢迎学长
考虑到js的不安全性,api v1 key和域名修改为php后端获取
修复了下不能内联到图像url的问题