Created
February 9, 2023 07:06
-
-
Save TatuLund/7a5d38f6bb89bb764eaf677e25364524 to your computer and use it in GitHub Desktop.
Example of how to paste an image from clipboard to view using JavaScript in Vaadin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package org.vaadin.tatu; | |
| import com.vaadin.flow.component.ClientCallable; | |
| import com.vaadin.flow.component.html.Image; | |
| import com.vaadin.flow.component.html.Span; | |
| import com.vaadin.flow.component.orderedlayout.VerticalLayout; | |
| import com.vaadin.flow.router.Route; | |
| @Route("paste") | |
| public class PasteImage extends VerticalLayout { | |
| private Image image; | |
| public PasteImage() { | |
| Span span = new Span("Paste image with ctrl+v"); | |
| image = new Image("", "Preview"); | |
| image.setVisible(false); | |
| getElement().executeJs("function setPreviewImage(file) {const fileReader = new FileReader(); fileReader.readAsDataURL(file); fileReader.onload = () => { $0.$server.setImage(fileReader.result); }; } ; window.addEventListener('paste', e => {if (e.clipboardData.files.length > 0 && e.clipboardData.files[0].type.startsWith('image/')) { setPreviewImage(e.clipboardData.files[0]); }; })", this.getElement()); | |
| add(span, image); | |
| } | |
| @ClientCallable | |
| private void setImage(String data) { | |
| image.setVisible(true); | |
| image.setSrc(data); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suppose we should first call fileReader.onload to setup callback and then call fileReader.readAsDataURL