概述

我的网站上有一个自用的云记事本,基于PHP+MySQL,最初作者为wusiyu冒泡鱼进行了一些优化,我进一步地做了一些修改和修复。目前我将此记事本中的ACE Editor更改为国人开发的Editor.md待解决完各种BUG后,我会将其发布出来。(安全可能有问题,自己用了?)
本文是介绍如何将Editor.md的图片上传改为七牛

Editor.md 是一款开源的、可嵌入的 Markdown 在线编辑器,基于 CodeMirror、jQuery 和 Marked 构建。项目地址https://github.com/pandao/editor.md

开启图片上传

官网的文档中说明,我们需要添加下方代码框的后3个属性

var editor = editormd("test-editor", {
        // width  : "100%",
        // height : "100%",
        path   : "editormd/lib/",
    imageUpload    : true,//开启图片上传
        imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],//接受的格式
        imageUploadURL : "./upload.php"//处理上传请求的链接地址
});

分析

点击上传后,后端需要获取名为editormd-image-file的图片数据,在处理完上传请求后返回一个JSON,若成功上传则返回图片链接和success状态码1,否则返回0。

在PHP中,我们可以通过以下方法获取上传的图片的一些信息

//上传的文件名
$_FILES["editormd-image-file"]["name"]
//上传到服务器的临时文件位置
$_FILES["editormd-image-file"]["tmp_name"]

实测效果

实测的效果

需要注意的是,此处的剪切板图片粘贴上传使用了image-handle-paste.js插件,你可以自行搜索添加。

完整代码(七牛)

SDK下载地址

<?php
require_once 'qnsdk/autoload.php'; //引入七牛的sdk
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class uploadImage{
    public $access_key;
    public $secret_key;
    public $bucket;
    public $domain;
    public $path;
    public $filename;
  
    public function __construct(){
        //access_key
        $this->access_key = '';
        //secret_key
        $this->secret_key = '';
        //存储空间bucket名字
        $this->bucket = '';
        //七牛绑定的域名,最后的斜杠一定要带
        $this->domain = 'https://example.com/';
        //上传的路径
        $this->path = 'note_pic/';
        //上传的文件名
        $this->filename = $this->randString()."_".$_FILES["editormd-image-file"]["name"];
    }
  
    function randString() {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for($a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',$f = 0;$f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;
    }
  
    public function uploadImg($imageData){
        // 初始化签权对象
        $auth  = new Auth($this->access_key, $this->secret_key);
        // 生成上传Token
        $token = $auth->uploadToken($this->bucket);
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        list($rest, $uperr) = $uploadMgr->putFile($token,$this->path.$this->filename, $imageData);
        $json = new \stdClass();
        if ($uperr) {
            $json->success=0;
            $json->message=$uperr;
        }else {
            $json->success=1;
            $json->url=$this->domain.$this->path.$this->filename;
        }
        echo json_encode($json,JSON_UNESCAPED_UNICODE);
    }
}

$upTest = new uploadImage();
//var_dump($_FILES["editormd-image-file"]);
$upTest->uploadImg($_FILES["editormd-image-file"]["tmp_name"]);

完整代码(腾讯云COS)

SDK下载地址(请选择Guzzle7版本)

<?php
require_once 'tencent-php/vendor/autoload.php'; //引入sdk

class uploadImage
{
    public $secretId;
    public $secretKey;
    public $bucket;
    public $domain;
    public $path;
    public $filename;

    public function __construct()
    {
        //secretId
        $this->secretId = '';
        //secretKey
        $this->secretKey = '';
        //存储桶名称
        $this->bucket = '';
        //地域ap-xxxxx
        $this->region = '';
        //存储桶域名或绑定的CDN域名,最后的斜杠一定要带
        $this->domain = 'https://example.com/';
        //上传的路径,最后的斜杠一定要带
        $this->path = 'note_pic/';
        //上传的文件名
        $this->filename = $this->randString() . "_" . $_FILES["editormd-image-file"]["name"];
        //cosClient
        $this->cosClient = new Qcloud\Cos\Client(array(
            'region' => $this->region,
            'schema' => 'https',
            'credentials' => array(
                'secretId' => $this->secretId,
                'secretKey' => $this->secretKey
            )
        ));
    }

    function randString()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for ($a = md5($rand, true),
             $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
             $d = '', $f = 0; $f < 8;
             $g = ord($a[$f]),
             $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
             $f++
        ) ;
        return $d;
    }

    public function uploadImg($imageData)
    {
        $json = new \stdClass();
        try {
            $result = $this->cosClient->upload(
                $bucket = $this->bucket,
                $key = $this->path . $this->filename,
                $body = fopen($imageData, 'rb')
            );
            // print_r($result);
            $json->success = 1;
            $json->url = $this->domain . $this->path . $this->filename;
        } catch (\Exception $e) {
            $json->success = 0;
            // echo (string)$e;
            $json->message = "上传失败";
        }
        echo json_encode($json, JSON_UNESCAPED_UNICODE);
    }
}

$upTest = new uploadImage();
//var_dump($_FILES["editormd-image-file"]);
$upTest->uploadImg($_FILES["editormd-image-file"]["tmp_name"]);

这样我们就实现了图片上传的功能,请自行添加判断是否登陆的代码

Editor.md表情修复

将以下代码加入Editor.md的onload事件中

editormd.emoji = {
     path  : "https://cdn.staticfile.org/emoji-cheat-sheet/1.0.0/",
     ext   : ".png"
 };
 editormd.twemoji = {
    path : "https://cdn.staticfile.org/twemoji/1.0.0/36x36/",
    ext  : ".png"
    };
最后修改:2024 年 11 月 08 日
如果觉得我的文章对你有用,请随意赞赏或点击右侧广告位(若看不到请关闭广告屏蔽)
END
本文作者:
文章标题:Markdown编辑器Editor.md图片上传到七牛
本文地址:https://wanghongfeng.cn/editormd_uploadimg.html
版权说明:若无注明,本文皆王洪峰's blog原创,转载请保留文章出处。