3

暂时我还没有把这个做成一个插件,只是简单的几行代码。其中原理就是通过截图后,ev.clipboardData 包含了text和图片文件 数据

原文链接:http://blog.oeynet.com/post/7...

screenshots.png

1.Js监听paste事件

seajs.use(['editormd'], function (editormd) {
            var editor = editormd({
                id: "post_content",
                height: 840,
                path: "/static/libs/editor.md/lib/",
                toolbarIcons: function () {
                    // Or return editormd.toolbarModes[name]; // full, simple, mini
                    // Using "||" set icons align right.
                    return ["undo", "redo", "|", "bold", "hr", "|", "preview", "watch", "|", "fullscreen", "info", "testIcon", "testIcon2", "file", "faicon", "||", "watch", "fullscreen", "preview", "testIcon"]
                },
                //toolbar  : false,             // 关闭工具栏
                codeFold: true,
                searchReplace: true,
                saveHTMLToTextarea: true,      // 保存 HTML 到 Textarea
                htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析,为了安全性,默认不开启
                emoji: true,
                taskList: true,
                tocm: true,          // Using [TOCM]
                tex: true,                      // 开启科学公式 TeX 语言支持,默认关闭
                //previewCodeHighlight : false,  // 关闭预览窗口的代码高亮,默认开启
                flowChart: true,                // 疑似 Sea.js与 Raphael.js 有冲突,必须先加载 Raphael.js ,Editor.md 才能在 Sea.js 下正常进行;
                sequenceDiagram: true,          // 同上
                //dialogLockScreen : false,      // 设置弹出层对话框不锁屏,全局通用,默认为 true
                //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层,全局通用,默认为 true
                //dialogDraggable : false,    // 设置弹出层对话框不可拖动,全局通用,默认为 true
                //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度,全局通用,默认值为 0.1
                //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色,全局通用,默认为 #fff
                imageUpload: true,
                imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                imageUploadURL: "{:url('api/uploader/uploadEditorImg?pic_type=10')}",
                onload: function () {
                    this.on('paste', function () {
                        console.log(1);
                    });
                }
            });


            /**
             * 咱贴上传图片
             */
            $("#post_content").on('paste', function (ev) {
                var data = ev.clipboardData;
                var items = (event.clipboardData || event.originalEvent.clipboardData).items;
                for (var index in items) {
                    var item = items[index];
                    if (item.kind === 'file') {
                        var blob = item.getAsFile();
                        var reader = new FileReader();
                        reader.onload = function (event) {
                            var base64 = event.target.result;
                            //ajax上传图片
                            $.post("{:url('api/uploader/upEditorImg')}",{base:base64}, function (ret) {
                                layer.msg(ret.msg);
                                if (ret.code === 1) {
                                    //新一行的图片显示
                                    editor.insertValue("\n![" + ret.data.title + "](" + ret.data.path + ")");
                                }
                            });
                        }; // data url!
                        var url = reader.readAsDataURL(blob);
                    }
                }
            });

        });

这是一个完整的示例,其中

$("#post_content") 便是监听paste事件

2.PHP处理

public function upEditorImg()
    {
        $token = Session::get('user_token');
        if (!$token || $token['id'] <= 0) {
            $this->error("对不起,您没有权限操作");
        }
        // 获取表单上传文件 例如上传了001.jpg
        $base64 = input('base');
        $savePath = Config::get("storage_path.editor");
        $file = Utils::saveBase642Img($base64, $savePath);
        if (!$file) {
            $this->result([], 500, "上传失败,请检查上传文件");
        }
        // 移动到框架应用根目录/public/uploads/ 目录下

        if ($file->check(['size' => 1024 * 1024 * 1, 'ext' => 'jpg,png,jpeg,gif'])) {
            $entity = [
                'create_time' => time(),
                'title' => $file->getInfo('name'),
                'size' => $file->getInfo('size'),
                'ext' => $file->getExtension(),
                'type' => $file->getInfo('type'),
                'path' => "/upload/editor" . $file->getInfo('build_path'),
                'md5' => $file->md5(),
                'uid' => $token['id'],
            ];
            $pic = new BbsPicture();
            $ret = $pic->insertGetId($entity);
            if (!$ret) {
                $this->result([], 500, "上传失败,请稍后重试");
            }
            $entity['title'] = "screenshots.{$entity['ext']}";
            $this->result($entity, 1, "上传成功", "Json");
        } else {
            $this->result([], 0, $file->getError(), "Json");
        }
    }

PHP使用了ThinkPHP框架,其中Utils是个人封装的一个base64得

    /**
     * @param $content
     * @param $path
     * @return bool|File
     */
    static public function saveBase642Img($content, $path)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result)) {
            $type = $result[2];
            $file['type'] = "images/" . $type;
            $file['ext'] = $type;
            $file['save_path'] = $path . DS . date('Ymd') . DS;
            if (!is_dir($file['save_path'])) {
                mkdir($file['save_path'], 0777);
            }
            $file['data'] = base64_decode(str_replace($result[1], '', $content));
            $file['name'] = md5($file['data']) . ".{$file['ext']}";
            if (!file_put_contents($file['save_path'] . $file['name'], $file['data'])) {
                return false;
            }
            unset($file['data']);
            $FILE = new File($file['save_path'] . $file['name']);
            $file['size'] = $FILE->getSize();
            $file['saveName'] = $file['save_path'] . $file['name'];
            $file['build_path'] = DS . date('Ymd') . DS . $file['name'];

            $FILE->setUploadInfo($file);
            return $FILE;
        } else {
            return false;
        }
    }

参考


Godtoy
2.4k 声望114 粉丝

Technology change the 'hello world'