天天看點

summernote富文本編輯器的自定義附件上傳:不限于圖檔類型前言一、自定義上傳附件按鈕和彈窗二、結合PHP上傳檔案進行後端處理三、用jq模拟點選添加連結方式去處理上傳附件

summernote富文本編輯器的自定義附件上傳

  • 前言
  • 一、自定義上傳附件按鈕和彈窗
  • 二、結合PHP上傳檔案進行後端處理
  • 三、用jq模拟點選添加連結方式去處理上傳附件

前言

summernote的上傳有圖檔上傳隻能上傳圖檔,附件上傳插件uploadcare-summernote上傳的檔案不在指定的伺服器,是以自己修改了一下的插傳入連結接的方式上傳附件功能,此功能可自定義上傳檔案類型,不隻限于圖檔上傳!!!完全可以自定義上傳類型

思路:通過插傳入連結接的方式去把自定義上傳在自己指定伺服器生成的 路徑連結 和 檔案名 插入編輯器,進而達到一個白嫖的附件上傳效果。

一、自定義上傳附件按鈕和彈窗

  1. 可以參考官方文檔先自定義一個按鈕插件–附件上傳,友善的可直接下載下傳我的附件。其實很多部落格也有添加自定義的插件方法,找找就有。

    我的檔案中主要是一個簡單的彈窗上傳檔案頁面,這個頁面可以自定義。

this.createDialog = function () {
	var $box = $('<div />');
	//變量$yaya 是彈窗中顯示的上傳檔案頁面,具體的自定義樣式排版等
    var $yaya = $('<form name="addForm" id="thinkassUploadFile" action="your web upload_file action" method="post" enctype="multipart/form-data"><div class="form-group"><input type="file" id="macFile" name="macFile" οnchange="thinkassUploadFile()"><div id="message"><div></div></form>');
    $box.append($yaya);
    return $box.html();
};
           
  1. 引入下載下傳的檔案,然後再初始化的時候把按鈕添加上即可 [‘insert’, [‘upload_file’]]
$(document).ready(function() {
    var $summernote = $('#tseditor').summernote({

        toolbar: [
            ['cleaner',['cleaner']],
            ['style', ['style']],
            ['font', ['bold', 'underline', 'clear']],
            //['fontname', ['fontname']],
            ['fontsize', ['fontsize']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['table', ['table']],
            //重點!!!在這裡引入檔案中的函數名稱 upload_file
            ['insert', ['link','unlink', 'picture','upload_file']],
            ['highlight', ['highlight']],
            ['view', ['fullscreen']],
        ],
        cleaner:{
            action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
            newline: '<br>', // Summernote's default is to use '<p><br></p>'
            notStyle: 'position:absolute;top:0;left:0;right:0', // Position of Notification
            icon: '<i class="note-icon">[清理HTML]</i>',
            keepHtml: true, // Remove all Html formats
            keepOnlyTags: ['<p>', '<br>', '<ul>', '<li>', '<b>', '<strong>','<i>', '<a>','<img>'], // If keepHtml is true, remove all tags except these
            keepClasses: true, // Remove Classes
            badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], // Remove full tags with contents
            badAttributes: ['style', 'start'], // Remove attributes from remaining tags
            limitChars: false, // 0/false|# 0/false disables option
            limitDisplay: 'both', // text|html|both
            limitStop: false // true/false
        },

        placeholder:'開始創作吧...',
        height:300,
		lang: 'zh-CN',
		
		callbacks: {
			onChange: function(contents, $editable) {
				//console.log('onChange:', contents, $editable);
				content.val(contents)
			},
			//這個是上傳圖檔的回調位址,上傳其他附件識别不到,這個可以重新把上傳圖檔的路徑改成自定義sendFile方法是我自定義上傳圖檔的方法
            onImageUpload: function(files) {
                // upload image to server and create imgNode...
				// $summernote.summernote('insertNode', imgNode)
				//console.log(files[0])
                sendFile($summernote, files[0]);

            }

        }
		
    });
           

效果圖:

summernote富文本編輯器的自定義附件上傳:不限于圖檔類型前言一、自定義上傳附件按鈕和彈窗二、結合PHP上傳檔案進行後端處理三、用jq模拟點選添加連結方式去處理上傳附件

二、結合PHP上傳檔案進行後端處理

網上搜尋一大把—我的是結合thinksaas的處理,直接上代碼:

//本地上傳檔案存儲
function uploadFileLocal($file, $fileDir)
{
    if (!isset($file)) {
        return [
            'code'=>1,
            'message'=>'上傳的檔案為null',
            'url'=>''
        ];
        
    }
    if (!file_exists('uploadfile/' . $fileDir)) {
        mkdir(iconv("UTF-8", "GBK", 'uploadfile/' . $fileDir),0777,true);
    }
    $fileName=$file["name"];
    $fileSize = $file["size"];
    $fileType = strstr($fileName, ".");
    if ($fileSize>$GLOBALS['TS_SITE']['attach_size'] * 1048576) { // 5M--->512*1024*1024 $GLOBALS['TS_SITE']['attach_size']直接替換成數字
        return [
            'code'=>1,
            'message'=>'大小不能超過'.$GLOBALS['TS_SITE']['attach_size'].'MB,請重新選擇',
            'url'=>''
        ];
    }
    //檔案類型過濾:$GLOBALS['TS_SITE']['attach_type']
    if (!in_array(substr($fileType,1), explode(",", $GLOBALS['TS_SITE']['attach_type']))) {
        return [
            'code'=>1,
            'message'=>'檔案格式隻允許'.$GLOBALS['TS_SITE']['attach_type'],
            'url'=>''
        ];
    }
    $pics = rand(1, 9999) . $fileName;//時間戳/随機數/檔案字尾
    iconv("UTF-8", "GBK", 'uploadfile/' . $fileDir . '/' . $pics); //檔案轉義
    //将臨時檔案移動到指定目錄
    $savFile= move_uploaded_file($file["tmp_name"], 'uploadfile/' . $fileDir . '/' . $pics);
    if ($savFile) {
        return [
            'code'=>0,
            'message'=>'success',
            'url'=>'uploadfile/' . $fileDir . '/' . $pics
        ];
    } else {
        return [
            'code'=>1,
            'message'=>'上傳的檔案儲存失敗',
            'url'=>''
        ];
    }
}
           

三、用jq模拟點選添加連結方式去處理上傳附件

以下代碼可能會有浏覽器不用相容的場景,需自行解決。

處理上傳檔案代碼如下(示例):

//處理檔案商場
function thinkassUploadFile() {

        var formData = new FormData(document.getElementById('thinkassUploadFile'));
        $.ajax({
            url:"指定到後端處理問價上傳的方法uploadFileLocal",
            type:"post",
            data:formData,
            dataType: 'json',
            processData:false,// 告訴jQuery不要去處理發送的資料
            contentType:false,// 告訴jQuery不要去設定Content-Type請求頭
            success:function(data){
                if (data.code===0) {
                    var html = '<p class="text-success">檔案上傳成功:請關閉目前彈窗(如果未自動複制,請手動複制),然後手動添加連結 <i class="note-icon-link"></i>,把所複制内容填進<連結位址></p><br/><p><span class="text-danger">'+data.url+'</span></p>';
                    $("#message").html(html);
                    $(".footer").append('<div style="diaplay:none" class="appendHide"><input id="hide" type="text" style="opacity: 0" value="'+data.url+'"></div>');
                    copyAndInsert(data.url);
                }else{
                    var html = '<p>附件上傳失敗:<i class="text-danger">'+data.message+'</i></p>';
                    $("#message").html(html);
                }
            },
            error:function(e){
                $("#uploderr").html(data.message)
            }
        });
}
//處理模拟插傳入連結接的按鈕把生成的上傳到伺服器的檔案位址插入
function copyAndInsert(url) {
    var hide=document.getElementById("hide");
    hide.select(); // 選擇對象
    document.execCommand("Copy"); // 執行浏覽器複制指令
    //alert("已自動複制好生成的附件連結,即将到插傳入連結接頁面進行操作");
    alert("已自動複制好生成的附件連結,若插入失敗請更換 谷歌浏覽器 或者 360浏覽器極速模式 再試");
    $(".appendHide").remove();
    $(".upload_file").removeClass("open");
    $(".note-modal-backdrop").remove();
    //模拟點選插傳入連結接按鈕
    $(".note-icon-link").trigger("click");
    //把連結指派到插傳入連結接位址中
    $(':focus').val(url);
    var id = $(':focus').attr('id');
    //附件标題--連結文本
    var newstart = id.replace(/url/, "txt");
    //動态擷取附件名稱
    var fileName =url.substr(url.lastIndexOf('/')+1);
    $("#"+newstart).trigger("focus");
    //把檔案名稱指派到連結的顯示文本中
    $("#"+newstart).val(fileName);
    //去掉插傳入連結接的禁用屬性
    var insert = $("#"+newstart).parent().parent().next().children("input");
    insert.removeClass("disabled").removeAttr("disabled");
    //模拟點選送出按鈕
    $(insert).trigger("click");
}
           

就是這麼簡單!!!以上内容如有侵權請聯系我謝謝~

轉載請标明出處謝謝~

繼續閱讀