How to paste Files from the Clipboard using JavaScript
First, we register the document.onpaste
function which gets called whenever a user pastes into your document. The first parameter of the function is the event.
The first thing we do in this function is to get the file from the paste event. After that, we check if a file has been pasted, if not, we cancel the excution. Otherwise we use that image in this case to upload it to an endpoint.
document.addEventListener('DOMContentLoaded', () => {
document.onpaste = function(event){
const file = getFileFromPasteEvent(event);
if (!file) { return; }
uploadImage(file);
}
});
How does the getFileFromPasteEvent
function work? First we get all the clipboardData, then we iterate through them. We check for every item if it’s kind is a file
in which case the function returns that specific item as a file item.getAsFile()
.
function getFileFromPasteEvent(event) {
const items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (let index in items) {
const item = items[index];
if (item.kind === 'file') {
return item.getAsFile();
}
}
}
After we got the file from the paste event, you can handle this file object just the way you would handle a file object you receive from an input onchange event. In this case, we simply call an endpoint /posts/upload_image
which responds a JSON object with one key url
. This URL is the URL to the uploaded image like https://webdevchallenges.com/uploads/file_upload/image/32/image.png
for example.
function uploadImage(file) {
const data = new FormData();
data.append('file', file, file.name);
const options = {
method: 'POST',
headers: {
'X-CSRF-Token': document.querySelector("[name='csrf-token']").content
},
body: data
};
fetch('/posts/upload_image', options)
.then(response => response.json())
.then(json => insertImageToEditor(json.url));
}
As you can see, after retrieving that URL, I call a function insertImageToEditor
which adds Markdown to my CodeMirror editor at the current position of the cursor. The markdown it adds leads to the image being displayed. In case you’re interested in that, here’s the code for that. Note: the variable editor
references the CodeMirror editor which is available in this case.
function insertImageToEditor(url) {
const doc = editor.getDoc();
const cursor = doc.getCursor(); // gets the line number in the cursor position
const line = doc.getLine(cursor.line); // get the line contents
const pos = { // create a new object to avoid mutation of the original selection
line: cursor.line,
ch: line.length - 1 // set the character position to the end of the line
}
const imageText = '\n';
doc.replaceRange(imageText, pos); // adds a new line
}
Disclaimer: Most of this code was shamelessly copied.