Class: CKEditor5::Rails::Plugins::SimpleUploadAdapter

Inherits:
Editor::PropsInlinePlugin show all
Defined in:
lib/ckeditor5/rails/plugins/simple_upload_adapter.rb

Constant Summary collapse

PLUGIN_CODE =
"import { Plugin, FileRepository } from 'ckeditor5';\n\nexport default class SimpleUploadAdapter extends Plugin {\n  static get requires() {\n    return [FileRepository];\n  }\n\n  static get pluginName() {\n    return 'SimpleUploadAdapter';\n  }\n\n  init() {\n    const fileRepository = this.editor.plugins.get(FileRepository);\n    const config = this.editor.config.get('simpleUpload');\n\n    if (!config || !config.uploadUrl) {\n      console.warn('Upload URL is not configured');\n      return;\n    }\n\n    fileRepository.createUploadAdapter = (loader) => ({\n      async upload() {\n        try {\n          const file = await loader.file;\n          const formData = new FormData();\n          formData.append('upload', file);\n\n          return new Promise((resolve, reject) => {\n            const xhr = new XMLHttpRequest();\n\n            xhr.open('POST', config.uploadUrl, true);\n            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n\n            // Add CSRF token from meta tag\n            const csrfToken = document.querySelector('meta[name=\"csrf-token\"]')?.content;\n\n            if (csrfToken) {\n              xhr.setRequestHeader('X-CSRF-Token', csrfToken);\n            }\n\n            xhr.upload.onprogress = (evt) => {\n              if (evt.lengthComputable) {\n                loader.uploadTotal = evt.total;\n                loader.uploaded = evt.loaded;\n              }\n            };\n\n            xhr.onload = () => {\n              if (xhr.status >= 200 && xhr.status < 300) {\n                const data = JSON.parse(xhr.response);\n                resolve({ default: data.url });\n              } else {\n                reject(`Upload failed: ${xhr.statusText}`);\n              }\n            };\n\n            xhr.onerror = () => reject('Upload failed');\n            xhr.onabort = () => reject('Upload aborted');\n\n            xhr.send(formData);\n            this._xhr = xhr;\n          });\n        } catch (error) {\n          throw error;\n        }\n      },\n\n      abort() {\n        if (this._xhr) {\n          this._xhr.abort();\n        }\n      }\n    });\n  }\n}\n"

Instance Attribute Summary

Attributes inherited from Editor::PropsInlinePlugin

#code, #name

Instance Method Summary collapse

Methods inherited from Editor::PropsInlinePlugin

#to_h

Constructor Details

#initializeSimpleUploadAdapter

Returns a new instance of SimpleUploadAdapter.



83
84
85
# File 'lib/ckeditor5/rails/plugins/simple_upload_adapter.rb', line 83

def initialize
  super(:SimpleUploadAdapter, PLUGIN_CODE)
end