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
Uploadfield is not feasible because the FileList (= model of a file input field) does not allow to add/append a newFileobject.(Working) Workaround: So my workaround is a
TextAreawith apaste-EventListener that does a remote procedure call of a@ClientCallablemethod at the server.Left component is the
TextArea, right component is a previewImage.Code:
Extendability: Instead of
previewImg.setSrcyou 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
Uploadcomponent:If you've got an
Uploadcomponent and want to extend it with this paste functionality, you can register thepastelistener at theUploadcomponent (or at some other component) and instead ofpreviewImg.setSrcyou just call this (whereas theonSucceededRunneris 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
Uploadfield plus aTextFieldfor 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.