Skip to content

Instantly share code, notes, and snippets.

@cryptoskillz
Last active April 9, 2023 16:17
Show Gist options
  • Save cryptoskillz/719b8a4a7a2872a650a4771b4c75de1b to your computer and use it in GitHub Desktop.
Save cryptoskillz/719b8a4a7a2872a650a4771b4c75de1b to your computer and use it in GitHub Desktop.
how to use a custom image uploader in any rich text image editor.
//overide the image handler, this is using quill but it will work with any richtext editor.
var toolbar = quill.getModule('toolbar');
toolbar.addHandler('image', showImageUI);
let saveToServer = (file) => {
//get the data
const fd = new FormData();
fd.append('image', file);
//send it ot the server
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/upload/image', true);
xhr.onload = () => {
if (xhr.status === 200) {
// this is callback data: url
const url = JSON.parse(xhr.responseText).data;
//insert the new image into the editor
insertToEditor(url);
}
};
xhr.send(fd);
}
//insert image url to rich editor.
function insertToEditor(url) {
// push image url to rich editor.
const range = editor.getSelection();
editor.insertEmbed(range.index, 'image', `http://localhost:9000${url}`);
}
//show the image upload dialog
let showImageUI = () => {
//create in input
const input = document.createElement('input');
//set the type
input.setAttribute('type', 'file');
//restrict it to images
input.setAttribute('accept', 'image/*');
//open it.
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files[0];
saveToServer(file);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment