My need: I'd like to add an "upload from clipboard" functionality into a Vaadin 23 application so that the user can paste a screenshot into an Upload
field.
Known pieces of the puzzle: I know that there is a paste
event (see here https://stackoverflow.com/a/51586232/10318272 or here https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event ) and there's the Vaadin Upload
component ( https://vaadin.com/docs/latest/components/upload ).
Question: How can I transfer the pasted data into the Upload
field?
Why initially intended solution does not work: It seems that uploading a screenshot via an
Upload
field is not feasible because the FileList (= model of a file input field) does not allow to add/append a newFile
object.(Working) Workaround: So my workaround is a
TextArea
with apaste
-EventListener that does a remote procedure call of a@ClientCallable
method at the server.Left component is the
TextArea
, right component is a previewImage
.Code:
Extendability: Instead of
previewImg.setSrc
you could do whatever you want with the uploaded file. The preview is just the proof that the screenshot goes to the server (and could go back to the client again).Possible connection to
Upload
component:If you've got an
Upload
component and want to extend it with this paste functionality, you can register thepaste
listener at theUpload
component (or at some other component) and instead ofpreviewImg.setSrc
you just call this (whereas theonSucceededRunner
is aBiConsumer<String, String>
in my case that runs the onSucceeded stuff (updating thumbnails, setting attributes at the bound bean, ...)):Final result:
This is what my custom upload field looks like in the end (assembled from the code above plus an
Upload
field plus aTextField
for the file name and a thumbnail preview). The user now has to click somewhere at that field (=focus it, because there could be more than one in a form), press Ctrl+V and then a screenshot gets uploaded (if there is any) from clipboard to Vaadin application at the server.