Upload images from clipboard

Basic example for upload images from clipboard. This example can be use for example in TinyMCE as new modules for direct upload.

HTML

<input id="nameFile" type="text" placeholder="Name file">
<div class="container">
      <div>
            <div><kbd class="key">Ctrl</kbd> + <kbd class="key">V</kbd> in this window.</div>
            <img class="preview" id="preview" />
       </div>
</div>
<div class="result"></div>

CSS

.container {
  /* Center the content */
  align-items: center;
  display: flex;
  justify-content: center;

  /* Misc */
  height: 32rem;
  padding: 1rem 0;
}

.key {
  background-color: #f7fafc;
  border: 1px solid #cbd5e0;
  border-radius: 0.25rem;
  padding: 0.25rem;
}

.preview {
  align-items: center;
  border: 1px solid #cbd5e0;
  display: flex;
  justify-content: center;

  margin-top: 1rem;
  max-height: 16rem;
  max-width: 42rem;
}

JavaScript

document.addEventListener('paste', function (evt, api) {
	const clipboardItems = evt.clipboardData.items;
	const items = [].slice.call(clipboardItems).filter(function (item) {
		return item.type.indexOf('image') !== -1;
	});
	if (items.length === 0) {
		return;
	}

	var nameFile = $("#nameFile").val();
	if(nameFile==""){
		nameFile=Math.random().toString(36).substring(2,7)+".jpg";
	}else{
		nameFile=nameFile+".jpg";
	}

	const item = items[0];
	const blob = item.getAsFile();

	const imageEle = document.getElementById('preview');
	imageEle.src = URL.createObjectURL(blob);

	const formData = new FormData();
	formData.append('fileToUpload', blob, nameFile);

	const req = new XMLHttpRequest();

	req.open('POST', '/PATH/TO/SCRIPT/FOR/UPLOAD/WITH/AJAX', true); 
  // Change path to script for upload. For example PHP> move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

	req.onload = function () {
		if (req.status >= 200 && req.status < 400) {
			const res = req.responseText;
			// Do something with the response
			$('.result').html('File <b>'+nameFile+'</b> was upload.');
		}else{
    	$('.result').html('File <b>'+nameFile+'</b> was not upload <br>You have to set path to upload script.');
    }
	};

	req.send(formData);

});