We needed a way to upload image file on drag & drop event in CKeditor.
class Editor extends ClassicEditor {
insertHTML(html) {
const viewFragment = this.data.processor.toView(html);
const modelFragment = this.data.toModel(viewFragment);
this.model.insertContent(modelFragment);
}
getSelection() {
const selection = this.model.document.selection;
const range = selection.getFirstRange();
for (const item of range.getItems()) {
console.log(item.data) //return the selected text
}
}
handleAndDragDropEvent() {
this.editing.view.document.on('drop', function (evt, data) {
let name = data.dataTransfer.files[0].name
let file = data.dataTransfer.files[0]
const formData = new FormData();
formData.append('image', file);
formData.append('name', name);
fetch('http://localhost:3000/image', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
let url = data.url;
console.log(url)
editor.insertHTML(`
<figure class="image ck-widget ck-widget_with-resizer ck-widget_selected" contenteditable="false">
<img src="${url}" />
</figure>`)
;
})
.catch(error => {
console.log(error);
});
})
}
}
<script>
Editor
.create(document.querySelector('.editor'), Editor.config )
.then(editor => {
window.editor = editor;
editor.handleAndDragDropEvent();
})
.catch(error => {
console.error(error);
});
</script>
Here is the Express server to test the upload
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/');
},
filename: function(req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
const app = express();
app.use(cors());
app.use(express.static('uploads'));
app.post('/image', upload.single('image'), function(req, res, next) {
res.json({
url: 'http://localhost:3000/' + req.file.originalname,
});
});
console.log("start")
app.listen(3000);