summernote实现图片上传至服务器功能2

先说说summernote吧,第一眼看到他是在网上一些后台模板中,简洁、漂亮、易用直接就吸引了我,再看看自己之前用的CKEditor,就略显的笨重了许多,于是就想着把CKEditor换成summernote。

但是还有一个问题就是summernote在上传图片的时候,会把图片转成图片的base64数据,存储起来实在是太庞大了,处理起来也不太方便,想着将其上传到服务器存储,然后返回图片路径。

下面是Demo:
intest.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>summerernote</title>
    <link href="./assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="./dist/summernote.css" rel="stylesheet">
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="./awesome-4.5/css/font-awesome.min.css" />
    <script src="./assets/js/jquery-1.11.3.min.js"></script>
    <script src="./assets/js/bootstrap.min.js"></script>
    <script src="./dist/summernote.min.js"></script>
    <script type="text/javascript">
    function sendFile(file, editor, welEditable) {
        data = new FormData();
        data.append("file", file);
        url = "http://www.unipcn.com/summernote/server.php?act=uploadImg";
        console.log('111111<>222222>>> '+url);
        $.ajax({
            data: data,
            type: "POST",
            url: url,
            cache: false,
            contentType: false,
            processData: false,
            success: function (url) {
                console.log('url:>>>'+url);
                console.log('editor:>>>'+editor);
                $('.summernote').summernote('insertImage', url, '插入图片');
            }
        });
    }
    $(function(){
        // onImageUpload callback
        $('.summernote').summernote({
            'height':300,
          callbacks: {
            onImageUpload: function(files,editor,welEditable) {
                console.error('Upload image start...');
                sendFile(files[0],editor,welEditable);
                console.error('Upload image end...');
            }
          }
        });

    });

            
    </script>
</head>
<body>

server.php

<?php
$action=isset($_REQUEST['act'])?trim($_REQUEST['act']):'';

if ('uploadImg'==$action) {
    if ($_FILES['file']['name']) {
        if (!$_FILES['file']['error']) {
            $name = md5(rand(100, 200));
            $ext = explode('.', $_FILES['file']['name']);
            $filename = $name . '.' . $ext[1];
            $destination = './uploads/imgs/' . $filename; //change this directory
            $location = $_FILES["file"]["tmp_name"];
            move_uploaded_file($location, $destination);
            echo 'http://www.unipcn.com/summernote/uploads/imgs/' . $filename;//change this URL
        }
        else
        {
          echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容