Skip to content

Instantly share code, notes, and snippets.

@TatuLund
Created February 9, 2023 07:06
Show Gist options
  • Select an option

  • Save TatuLund/7a5d38f6bb89bb764eaf677e25364524 to your computer and use it in GitHub Desktop.

Select an option

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
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);
}
}
@andreika63
Copy link
Copy Markdown

I suppose we should first call fileReader.onload to setup callback and then call fileReader.readAsDataURL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment