Attach files to `live_file_input` from js

Hello community,

I’ve been exploring the possibility of programmatically setting files in the browser and associating them with a live_file_input in a Phoenix LiveView application. I’ve attempted the following script, but it doesn’t seem to be working as expected:

let file = new File([e.detail.blob], "avatar_preview.png", { type: "image/png" }); let fileInput = document.querySelector('input[name="avatar_preview"]'); let dataTransfer = new DataTransfer(); dataTransfer.items.add(file); fileInput.files = dataTransfer.files; 

Unfortunately, the file does not appear to be assigned to the live_file_input as intended. I’ve tried various approaches, such as updating the files property multiple times, but without success.

Is there a way to programmatically update the live_file_input or its associated ref data attributes to achieve the desired file association? Any insights or guidance on how to approach this challenge would be greatly appreciated.

Thank you!

1 Like

found the solution

import LiveUploader from "phoenix_live_view/assets/js/phoenix_live_view/live_uploader" ///... const file = new File([blob], "avatar_preview.jpeg", { type: "image/jpeg" }); LiveUploader.trackFiles(fileInput, files) fileInput.dispatchEvent(new Event("input", {bubbles: true})) 

I didn’t find this necessary because in my case the vanilla approach with DataTransfer works fine (the live_file_input must be empty at the time you set its files though).

However, what I’m still missing is how to make it track progress when doing it this way. At first it’s stuck at 0% and next thing you know it uploaded. I imagine this is because I am bypassing its default mechanism, but it would help to know what else needs to be done so that it all works as if triggered by user.

UPDATE: False alarm. It works properly with progress and all. It was just that the file was too small. With bigger files the progress is shown.