Laravel解决Tinymce编辑文件上传csrf_token问题

本人快去上学了,大概有200余天不碰代码,先把这个解决方法记录下来免得日后忘记。

ps:这边我们直接使用tinymce的demo进行安排。

我的编辑器配置

tinymce.init({
                    selector: '#content',
                    //skin:'oxide-dark',
                     menubar:false,
                    language:'zh_CN',
                   plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave autoresize axupimgs',
                    toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                     styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
                     table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | axupimgs',
                    height: 650, //编辑器高度
                    min_height: 400,
                    /*content_css: [ //可设置编辑区内容展示的css,谨慎使用
                        '/static/reset.css',
                        '/static/ax.css',
                        '/static/css.css',
                    ],*/
                    fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
                    font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;知乎配置=BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi Micro Hei, sans-serif;小米配置=Helvetica Neue,Helvetica,Arial,Microsoft Yahei,Hiragino Sans GB,Heiti SC,WenQuanYi Micro Hei,sans-serif',
                    // image_class_list: [
                    // { title: 'None', value: '' },
                    // { title: 'Some class', value: 'class-name' }
                    // ],
                    //extended_valid_elements:'script[src]',
                    //
                    template_cdate_format: '[CDATE: %m/%d/%Y : %H:%M:%S]',
                    template_mdate_format: '[MDATE: %m/%d/%Y : %H:%M:%S]',
                    autosave_ask_before_unload: false,
                    toolbar_mode : 'wrap',
                    images_upload_base_path: '/',
                    images_upload_handler: function (blobInfo, succFun, failFun) {
                       var _token = document.querySelector('.layui-form > input[name="_token"]').value;
                        var xhr, formData;
                        var file = blobInfo.blob();//转化为易于理解的file对象
                        file._token = _token;
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', '/admins/files/upload_img');
                        xhr.onload = function() {
                            var json;
                            if (xhr.status != 200) {
                                failFun('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json || typeof json.location != 'string') {
                                failFun('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            succFun(json.location);
                        };
                        formData = new FormData();
                        formData.append('tinymce', file, file.name);//此处与源文档不一样
                        formData.append('_token',document.querySelector('.layui-form > input[name="_token"]').value);//此处与源文档不一样
                        xhr.send(formData);
                    }
                    //icons:'ax-color',
                });
图片上传+AX多图上传


images_upload_handler: function (blobInfo, succFun, failFun) {
                       var _token = document.querySelector('.layui-form > input[name="_token"]').value;
                        var xhr, formData;
                        var file = blobInfo.blob();//转化为易于理解的file对象
                        file._token = _token;
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', '/admins/files/upload_img');
                        xhr.onload = function() {
                            var json;
                            if (xhr.status != 200) {
                                failFun('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json || typeof json.location != 'string') {
                                failFun('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            succFun(json.location);
                        };
                        formData = new FormData();
                        formData.append('tinymce', file, file.name);//此处与源文档不一样
                        formData.append('_token',document.querySelector('.layui-form > input[name="_token"]').value);//此处与源文档不一样
                        xhr.send(formData);
                    }
这边用的是XML进行ajax操作所以多少解释一下关键代码。


  xhr = new XMLHttpRequest();//这一行是用来船舰一个xhr对象用的

 xhr.open('POST', '/admins/files/upload_img');//请求目标路径
xhr.onload = function() {
                            var json;
                            if (xhr.status != 200) {
                                failFun('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json || typeof json.location != 'string') {
                                failFun('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            succFun(json.location);
                        };
这一块是回调
formData = new FormData();//新建数据对象
                        formData.append('tinymce', file, file.name);//把上传的图片打包
                        formData.append('_token',document.querySelector('.layui-form > input[name="_token"]').value);//此处与源文档不一样
                        xhr.send(formData);//把larvel用的token打包一起发过去
这样子前端发送就完事了。

后端代码:laravel实现

public function upload_img(Request $request)
    {
        // $ss = $_FILES['']
        if ($request->hasFile('file')) {
            $path = $request->file('file')->store('public/thumb');
            $url = Storage::url($path);
            return json_encode(['code'=>0,'msg'=>'上传成功','data'=>['src'=>"$url"]]);
        }
        if ($request->hasFile('tinymce')) {
            $path = $request->file('tinymce')->store('public/tinymce/'.date('Y/m/d',time()));
            $url = Storage::url($path);
            return json_encode(['location'=>$url]);
        }
    }
如果使用laravel记得use一下 

use Illuminate\Support\Facades\Storage;

也可以自己写一个都一样的。

只要回调符合Tinymce要求就行了,这都是基本功就不多赘述了哈。


版权声明:若无特殊注明,本文为《周小雨》原创,转载请保留文章出处。
本文链接:https://zxyy.me/post-191.html
正文到此结束

热门推荐

管理员已关闭本篇文章评论!