Is it possible to trigger a live upload from client-side JS?

I’m pretty new to Phoenix, so bear with me here :pray:

I’m integrating the Trix editor (GitHub - basecamp/trix: A rich text editor for everyday writing) into a LiveView. I’ve got the text-editing features working, but now I’m working on file uploads, and I’m wondering if it is possible to use live uploads to make this work.

File uploads in Trix are accomplished by listening for a javascript event emitted by the editor on the client:

Storing Attached Files

Trix automatically accepts files dragged or pasted into an editor and inserts them as attachments in the document. Each attachment is considered pending until you store it remotely and provide Trix with a permanent URL.

To store attachments, listen for the trix-attachment-add event. Upload the attached files with XMLHttpRequest yourself and set the attachment’s URL attribute upon completion. See the attachment example for detailed information.

Is it possible to initiate a live upload from client-side javascript like this? If so, can anyone point me in the right direction on how to get started?

Much appreciated :pray:

phoenix hooks expose a this.upload/uploadTo function to do exactly that JavaScript interoperability — Phoenix LiveView v0.19.5

  • upload(name, files) - method to inject a list of file-like objects into an uploader.
  • uploadTo(selectorOrTarget, name, files) - method to inject a list of file-like objects into an uploader.
    The hook will send the files to the uploader with name defined by allow_upload/3
    on the server-side. Dispatching new uploads triggers an input change event which will be sent to the
    LiveComponent or LiveView the selectorOrTarget is defined in, where its value can be either a query selector or an
    actual DOM element. If the query selector returns more than one live file input, an error will be logged.
4 Likes

Oh bummer, I must have missed that when I looked through the docs. Thanks!