ckeditor 5 中的图像上传不适用于 laravel 8

mor*_*eza 2 php ckeditor laravel

我正在使用 Laravel 8 和 JavaScript 开发一个网站。我使用 ckeditor 5 并且运行良好。当我尝试上传照片时出现问题。照片上传已完成,但收到错误消息并且没有显示照片。我收到以下标题的错误:“无法上传文件:filename.jpg”我认为我没有向前端返回正确的响应。我在route/web.php文件中有这些代码

Route::group(["middleware"=>"auth","prefix"=>"panel"],function (){
    Route::post('/post/edit/{post_slug}', [PostController::class,"update"])->name("updatePostRoute");
    Route::get('/post/edit/{post_slug}', [RenderPanelController::class,"renderPostEditPage"])->name("renderPostEditPageRoute");
    Route::post('/post/ckeditor/upload', [PostController::class,"upload_image_cke"])->name('ckeditor.upload');
});
Run Code Online (Sandbox Code Playgroud)

在后控制器中

    public function upload_image_cke(Request $request){
        if ($request->hasFile('upload')) {
            $originName = $request->file('upload')->getClientOriginalName();
            $fileName = pathinfo($originName, PATHINFO_FILENAME);
            $extension = $request->file('upload')->getClientOriginalExtension();
            $fileName = $fileName . '_' . time() . '.' . $extension;

            $request->file('upload')->move(public_path('media'), $fileName);

            $CKEditorFuncNum = $request->input('CKEditorFuncNum');
            $url = asset('media/' . $fileName);
            $msg = 'upload successfully';
            $response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";

            @header('Content-type: text/html; charset=utf-8');
            echo $response;

        }
    }
Run Code Online (Sandbox Code Playgroud)

在刀片文件中:

<textarea type="text" class="form-control" name="content" id="content"></textarea>
<meta name="csrf-token" content="{{ csrf_token() }}">

<script src="https://cdn.ckeditor.com/ckeditor5/27.1.0/classic/ckeditor.js"></script>

<script>
    ClassicEditor
        .create( document.querySelector( '#content' ), {
            ckfinder: {
                uploadUrl: '{{route('ckeditor.upload')."?command=QuickUpload&type=Files&responseType=json"}}',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                }
            }
        },{
            alignment: {
                options: [ 'right', 'right' ]
            }} )
        .then( editor => {
            console.log( editor );
        })
        .catch( error => {
            console.error( error );
        })
</script>
Run Code Online (Sandbox Code Playgroud)

我需要返回什么响应才能使照片上传正常工作?

小智 8

我还有另一种方法可以做到。希望它对您和许多开发人员有用。

\n

我的做法是为每个用户动态定义一个存储路径($path_url变量)

\n

请注意,您必须运行php artisan storage:link请注意,您必须在终端上

\n

网页.php

\n
Route::post('ckeditor/upload', 'App\\Http\\Controllers\\CKEditorController@store')->name('ckeditor.upload');\n
Run Code Online (Sandbox Code Playgroud)\n

CKEditorController - 方法存储

\n
public function store(Request $request)\n   {\n      $path_url = 'storage/' . Auth::id();\n\n      if ($request->hasFile('upload')) {\n         $originName = $request->file('upload')->getClientOriginalName();\n         $fileName = pathinfo($originName, PATHINFO_FILENAME);\n         $extension = $request->file('upload')->getClientOriginalExtension();\n         $fileName = Str::slug($fileName) . '_' . time() . '.' . $extension;\n         $request->file('upload')->move(public_path($path_url), $fileName);\n         $url = asset($path_url . '/' . $fileName);\n      }\n\n      return response()->json(['url' => $url]);\n   }\n
Run Code Online (Sandbox Code Playgroud)\n

形式

\n
<textarea name="body" id="body" class="form-control"></textarea>\n
Run Code Online (Sandbox Code Playgroud)\n

现在,您必须定义一个“适配器”来将文件上传到存储

\n
<script src="https://cdn.ckeditor.com/ckeditor5/27.1.0/classic/ckeditor.js"></script>\n<script>\n    //Define an adapter to upload the files\n    class MyUploadAdapter {\n       constructor(loader) {\n          // The file loader instance to use during the upload. It sounds scary but do not\n          // worry \xe2\x80\x94 the loader will be passed into the adapter later on in this guide.\n          this.loader = loader;\n\n          // URL where to send files.\n          this.url = '{{ route('ckeditor.upload') }}';\n\n          //\n       }\n       // Starts the upload process.\n       upload() {\n          return this.loader.file.then(\n             (file) =>\n                new Promise((resolve, reject) => {\n                   this._initRequest();\n                   this._initListeners(resolve, reject, file);\n                   this._sendRequest(file);\n                })\n          );\n       }\n       // Aborts the upload process.\n       abort() {\n          if (this.xhr) {\n             this.xhr.abort();\n          }\n       }\n       // Initializes the XMLHttpRequest object using the URL passed to the constructor.\n       _initRequest() {\n          const xhr = (this.xhr = new XMLHttpRequest());\n          // Note that your request may look different. It is up to you and your editor\n          // integration to choose the right communication channel. This example uses\n          // a POST request with JSON as a data structure but your configuration\n          // could be different.\n          // xhr.open('POST', this.url, true);\n          xhr.open("POST", this.url, true);\n          xhr.setRequestHeader("x-csrf-token", "{{ csrf_token() }}");\n          xhr.responseType = "json";\n       }\n       // Initializes XMLHttpRequest listeners.\n       _initListeners(resolve, reject, file) {\n          const xhr = this.xhr;\n          const loader = this.loader;\n          const genericErrorText = `Couldn't upload file: ${file.name}.`;\n          xhr.addEventListener("error", () => reject(genericErrorText));\n          xhr.addEventListener("abort", () => reject());\n          xhr.addEventListener("load", () => {\n             const response = xhr.response;\n             // This example assumes the XHR server's "response" object will come with\n             // an "error" which has its own "message" that can be passed to reject()\n             // in the upload promise.\n             //\n             // Your integration may handle upload errors in a different way so make sure\n             // it is done properly. The reject() function must be called when the upload fails.\n             if (!response || response.error) {\n                return reject(response && response.error ? response.error.message : genericErrorText);\n             }\n             // If the upload is successful, resolve the upload promise with an object containing\n             // at least the "default" URL, pointing to the image on the server.\n             // This URL will be used to display the image in the content. Learn more in the\n             // UploadAdapter#upload documentation.\n             resolve({\n                default: response.url,\n             });\n          });\n          // Upload progress when it is supported. The file loader has the #uploadTotal and #uploaded\n          // properties which are used e.g. to display the upload progress bar in the editor\n          // user interface.\n          if (xhr.upload) {\n             xhr.upload.addEventListener("progress", (evt) => {\n                if (evt.lengthComputable) {\n                   loader.uploadTotal = evt.total;\n                   loader.uploaded = evt.loaded;\n                }\n             });\n          }\n       }\n       // Prepares the data and sends the request.\n       _sendRequest(file) {\n          // Prepare the form data.\n          const data = new FormData();\n          data.append("upload", file);\n          // Important note: This is the right place to implement security mechanisms\n          // like authentication and CSRF protection. For instance, you can use\n          // XMLHttpRequest.setRequestHeader() to set the request headers containing\n          // the CSRF token generated earlier by your application.\n          // Send the request.\n          this.xhr.send(data);\n       }\n       // ...\n    }\n\n    function SimpleUploadAdapterPlugin(editor) {\n       editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {\n          // Configure the URL to the upload script in your back-end here!\n          return new MyUploadAdapter(loader);\n       };\n    }\n\n    //Initialize the ckeditor\n    ClassicEditor.create(document.querySelector("#body"), {\n       extraPlugins: [SimpleUploadAdapterPlugin],\n    }).catch((error) => {\n       console.error(error);\n    });\n\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

我希望我有所帮助。一个拥抱!

\n