Open zhhangtaao opened 2 years ago
现如今很少有人自己做图片云存储了吧?各种云存储都来了(七牛,又拍云等....),而且还有免费的存储额度(每个月都有哦),对于个人博客/小站来说应该是够用了,editor.md自带是没有对接第三方云存储的,并且图片的上传方式也很逆天:用的iframe(为了兼容ie8?),什么年代了还用ie系列的浏览器?干毛线IT啊!!!(手动滑稽) 这你受得了吗?发哥反正是不能忍受的!
从今天起,这一切都会好转,换掉Iframe(Low B),迎接崭新的Formdata(gao da shang)!
首先声明,发哥的这些代码不是从0开始,没有深入研究editor.md的源代码(非专业前端也研究不出个啥),在github上看到了相关代码做了优化和调整,若原git作者看到了请发送原链接给我O(∩_∩)O~
https://github.com/jonny77/qiniu-upyun-for-editormd
1:兵马未动 粮草先行
后端先处理又拍云(authorization)和七牛云(token)的上传凭证,供前端使用直传模式上传图片
Laravel版:
<?php
/**
* Created by PhpStorm.
* User: liufa
* Date: 2018/12/26
* Time: 10:13
*/
namespace App\Http\Controllers;
class UpTokenController extends Controller
{
private $timeout = 3000;
private $allowDir = ['article', 'avatar', 'product', 'common'];//图片文件夹分类存储
private $uploadConfig = [
'qiniu' => [
//图片访问地址
'uploadServer' => 'http://up.qiniu.com/',
'viewBaseUrl' => 'http://pkfdqlk0e.bkt.clouddn.com/',
'bucket' => 'your bucket name',
//七牛的accessKey和secretKey,详见: https://portal.qiniu.com/user/key
'accessKey' => 'your accessKey',
'secretKey' => 'your secretKey',
],
'upyun' => [
'uploadServer' => 'http://v0.api.upyun.com/',
'viewBaseUrl' => 'http://fagework.test.upcdn.net/',
'bucket' => 'your bucket name',
//又拍云,使用的是"操作员",而不是密钥的方式,详见:https://console.upyun.com/account/operators/
'username' => 'user',
'password' => 'password'
]
];
private $savePath = '/';//文件保存路径
private $date;
public function __construct()
{
$dir = request('dirName');
if (!$dir || !in_array($dir, $this->allowDir)) {
return response()->json(['status' => false, 'message' => '上传路径有误,请指定']);
}
$this->savePath = $dir . '/' . date('Ym/d', time()) . md5(time() . rand(100, 1000000));
$this->date = gmdate('D, d M Y H:i:s \G\M\T');
}
//获取又拍云的授权
public function getTokenUpyun()
{
$config = $this->uploadConfig['upyun'];
$bucket = $config['bucket'];
$uri = "/" . $bucket;
$options = ["bucket" => $config['bucket'], "save-key" => $this->savePath, "expiration" => time() + ($this->timeout), "date" => $this->date];
$policy = base64_encode(json_encode($options));
$signature = base64_encode(hash_hmac("sha1", "POST&$uri&$this->date&$policy", md5($config['password']), true));
$json['date'] = $this->date;
$json['policy'] = $policy;
$json['authorization'] = "UPYUN " . $config['username'] . ":" . $signature;
$json['uploadServer'] = $config['uploadServer'] . $bucket;
$json['viewBaseUrl'] = $config['viewBaseUrl'];
$json['status'] = true;
return $json;
}
//获取七牛云上传授权
public function getTokenQiniu()
{
$config = $this->uploadConfig['qiniu'];
$returnBody = [
'saveKey' => '$(key)',
'name' => '$(fname)',
'size' => '$(fsize)',
'w' => '$(imageInfo.width)',
'h' => '$(imageInfo.height)',
'hash' => '$(etag)'
];
$policyData = array(
"scope" => $config['bucket'],
"deadline" => time() + 3600,
"returnBody" => json_encode($returnBody),
'saveKey' => $this->savePath
);
$data = json_encode($policyData);
$encodedPutPolicy = $this->safe_base64_encode($data);
$sign = hash_hmac('sha1', $encodedPutPolicy, $config['secretKey'], true);
$result = $config['accessKey'] . ':' . $this->safe_base64_encode($sign) . ':' . $encodedPutPolicy;
$json['authorization'] = $result;
$json['uploadServer'] = $config['uploadServer'];
$json['viewBaseUrl'] = $config['viewBaseUrl'];
$json['status'] = true;
return $json;
}
/**
* base64转码(七牛需要按此处理)
* @param $data
* @return mixed
*/
private function safe_base64_encode($data)
{
$find = array('+', '/');
$replace = array('-', '_');
return str_replace($find, $replace, base64_encode($data));
}
}
把文件放到Http/Controllers下面
在routes.php 中添加如下两行
Route::get('/getUploadToken/upyun', 'UpTokenController@getTokenUpyun');
Route::get('/getUploadToken/qiniu', 'UpTokenController@getTokenQiniu');
2:引入我们的editor.md.js和plugins(PS:我相信你知道如何让一个id为editormd的div变成一个富文本编辑器)
<script src="/static/editor.md/editormd.min.js"></script>
<script src="/static/editor.md/plugins/image-dialog-upyun/image-dialog-upyun.js"></script>
或
<script src="/static/editor.md/plugins/image-dialog-qiniu/image-dialog-qiniu.js"></script>
<script>
var editor = editormd("editormd", {
width: "100%",
height: 540,
syncScrolling: "single",
path : "{{ asset('/editor.md/lib/') }}/",
imageUpload: true,
imageFormats: ["jpg", "jpeg", "png"],
saveHTMLToTextarea: true,
toolbarIcons: function () {
return [
"undo", "redo", "bold", "del", "italic", "hr", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "list-ul", "list-ol", "|",
"link", "reference-link", "upyun", "table", "code", "code-block", "datetime", "|",
"goto-line", "preview", "watch", "|",
"fullscreen", "clear", "search"];
},
//云上传
toolbarIconsClass: {
upyun: "fa-cloud-upload"
},
toolbarHandlers: {
upyun: function () {
this.imageDialogUpyun()
// this.imageDialogQiniu()
}
},
uploaderTokenUrl: "/getUploadToken/upyun",
// uploaderTokenUrl: "/getUploadToken/qiniu",
dirName:'article'
});
</script>
七牛的使用和上面相似,只需要切换注释即可
此时此刻,通过机动地切换引入js和相关注释,应该已经可以将图片分别上传到七牛和又拍了. ///toto 其实image-dialog-qiniu.js和image-dialog-upyun.js的内容变化不大.只是在直传的时候,上传参数有些不同而已,有精力的同学可以继续优化以达到更优美的实现方式(使用一个js即可),调用的地方只需要指定上传到七牛/又拍云不是更优美么?
使用方法详见: http://b.fage.work/article/75
非常希望看到使用方法,请告知最新地址 谢谢