Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from wnm/ckeditor_controller.js
Created July 12, 2020 00:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kivanio/f670c5357874de1dbfdd5d224f5ef174 to your computer and use it in GitHub Desktop.
Save kivanio/f670c5357874de1dbfdd5d224f5ef174 to your computer and use it in GitHub Desktop.
import UploadAdapter from './upload_adapter';
function CustomUploadAdapterPlugin( editor ) {
editor.plugins.get( 'FileRepository' ).createUploadAdapter = ( loader ) => {
// Configure the URL to the upload script in your back-end here!
return new UploadAdapter( loader, editor );
};
}
import { Controller } from "stimulus"
export default class extends Controller {
connect(){
ClassicEditor
.create( this.element,
{
//...
extraPlugins: [ CustomUploadAdapterPlugin ],
customUpload: {
directUploadUrl: this.element.dataset.directUploadUrl,
blobUrlTemplate: this.element.dataset.blobUrlTemplate
}
//...
}
)
.then( editor => {
console.log( editor );
} )
.catch( error => {
console.error( error );
});
}
}
// ...
= form.text_area :content, data: { "controller" => "ckeditor", "direct-upload-url" => rails_direct_uploads_url, "blob-url-template" => rails_service_blob_url(":signed_id", ":filename") }
import { DirectUpload } from "@rails/activestorage"
export default class UploadAdapter {
constructor( loader, editor ) {
this.loader = loader;
this.editor = editor;
this.blobUrlTemplate = this.editor.config.get("customUpload.blobUrlTemplate")
this.directUploadUrl = this.editor.config.get("customUpload.directUploadUrl")
}
upload() {
return this.loader.file
.then( file => new Promise( ( resolve, reject ) => {
this.resolve = resolve;
this.reject = reject;
const directUpload = new DirectUpload(file, this.directUploadUrl, this)
directUpload.create(this.directUploadDidComplete.bind(this))
}));
}
directUploadWillStoreFileWithXHR(xhr) {
this.xhr = xhr;
xhr.upload.addEventListener("progress", event => {
if ( event.lengthComputable ) {
this.loader.uploadTotal = event.total;
this.loader.uploaded = event.loaded;
}
})
}
abort() {
if ( this.xhr ) {
this.xhr.abort();
}
}
directUploadDidComplete(error, attributes) {
if (error) {
this.reject(`Something went wrong with uploading the image. Please try again!`);
}
const url = this.createBlobUrl(attributes.signed_id, attributes.filename)
this.resolve({ default: url });
}
createBlobUrl(signedId, filename) {
return this.blobUrlTemplate
.replace(":signed_id", signedId)
.replace(":filename", encodeURIComponent(filename))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment