代码之家  ›  专栏  ›  技术社区  ›  Jagdish Sharma

如何使用tinymce编辑器上载图像

  •  0
  • Jagdish Sharma  · 技术社区  · 6 年前

    我在我的Laravel应用程序中使用tinymce编辑器,我想使用图像上载插件,为此我向post控制器发出post请求,但当我调用url时,我得到了错误 methodnotallowed异常

    以下是我的编辑器代码:

    tinymce.init({                              
     selector: '#description',
    convert_urls: false,
    statusbar: false,  
    
    plugins: 'image code print preview fullpage  searchreplace autolink directionality  visualblocks visualchars fullscreen image link    table charmap hr pagebreak nonbreaking  toc insertdatetime advlist lists textcolor wordcount   imagetools    contextmenu colorpicker textpattern media ',
        toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat |undo redo | image code| link fontsizeselect  | ',
    
        images_upload_url: '{{url("/admin/upload")}}',
    
        // override default upload handler to simulate successful upload
        images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
    
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '{{url("/admin/upload")}}');
          if(xhr.status = 400){  err= "Invalid file name or Extension";}else if(xhr.status = 500){  err="Server Error";}else if(xhr.status = 403){  err="Origin Denied";}
            xhr.onload = function() {
                var json;
    
                if (xhr.status != 200) {
                    failure('HTTP Error: ' + xhr.status +' '+err);
                    return;
                }
    
                json = JSON.parse(xhr.responseText);
    
                if (!json || typeof json.location != 'string') {
                    failure('Invalid JSON: ' + xhr.responseText);
                    return;
                }
    
                success(json.location);
            };
    
            formData = new FormData();
            formData.append('file', blobInfo.blob(), blobInfo.filename());
    
            xhr.send(formData);
        },
    });
    

    这是我使用的控制器:

    Route::prefix('admin')->group(function() {
    Route::post('/upload', 'tinyupload@store');
    });
    

    我的控制器逻辑是:

    public function store(Request $request)
    {
    
    
    // Allowed origins to upload images
    $accepted_origins = array("http://localhost", "http://107.161.82.130", "http://abhidemo.com");
    
    // Images upload path
    $imageFolder = "uploads/";
    
    reset($_FILES);
    $temp = $_FILES['file']['name'];
    if(is_uploaded_file($temp['tmp_name'])){
        if(isset($_SERVER['HTTP_ORIGIN'])){
            // Same-origin requests won't set an origin. If the origin is set, it must be valid.
            if(in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)){
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            }else{
                header("HTTP/1.1 403 Origin Denied");
                return;
            }
        }
    
        // Sanitize input
        if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])){
            header("HTTP/1.1 400 Invalid file name.");
            return;
        }
    
        // Verify extension
        if(!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))){
            header("HTTP/1.1 400 Invalid extension.");
            return;
        }
    
        // Accept upload if there was no origin, or if it is an accepted origin
        $filetowrite = $imageFolder . $temp['name'];
        $imagefull=$serverimg.$filetowrite;
        move_uploaded_file($temp['tmp_name'], $filetowrite);
    
        // Respond to the successful upload with JSON.
        echo json_encode(array('location' => $imagefull));
    } else {
        // Notify editor that the upload failed
        header("HTTP/1.1 500 Server Error");
    }
    
    
    }
    

    我所面临的问题是,当我试图通过编辑器将图像上传到服务器时,根据我的代码和方法,它错误地显示了错误的类型文件,不允许出现异常,即使我在两侧使用相同的方法帖子

    1 回复  |  直到 6 年前
        1
  •  4
  •   user7993010 user7993010    6 年前

    在js中添加此代码:

    <script>
         tinymce.init({                              
     selector: '#description',
    convert_urls: false,
    statusbar: false,  
    
    plugins: 'image code print preview fullpage  searchreplace autolink directionality  visualblocks visualchars fullscreen image link    table charmap hr pagebreak nonbreaking  toc insertdatetime advlist lists textcolor wordcount   imagetools    contextmenu colorpicker textpattern media ',
        toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat |undo redo | image code| link fontsizeselect  | ',
    
        image_title: true,
                automatic_uploads: true,
                images_upload_url: '{{url("/admin/upload")}}',
                file_picker_types: 'image',
                file_picker_callback: function(cb, value, meta) {
    
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.setAttribute('accept', 'image/*');
    
                    input.onchange = function() {
                        var file = this.files[0];
    
                        var reader = new FileReader();
                        reader.readAsDataURL(file);
                        reader.onload = function () {
                            var id = 'blobid' + (new Date()).getTime();
                            var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                            var base64 = reader.result.split(',')[1];
                            var blobInfo = blobCache.create(id, file, base64);
                            blobCache.add(blobInfo);
                            cb(blobInfo.blobUri(), { title: file.name });
                        };
                    };
                    input.click();
                }
            });
                                   </script><meta name="csrf-token" content="{{ csrf_token() }}" />
    

    在控制器中:

    public function store(Request $request) 
    { 
    
    $file=$request->file('file');
    $path= url('/uploads/').'/'.$file->getClientOriginalName();
    $imgpath=$file->move(public_path('/uploads/'),$file->getClientOriginalName());
    $fileNameToStore= $path;
    
    
    return json_encode(['location' => $fileNameToStore]); 
    
    }