Phoenix Liveview has a way of previewing the images you have selected and are about to upload to the server using:
<%= for entry <- @uploads.avatar.entries do %>
<.live_img_preview entry={entry} width="75" />
<% end %>
I would like to make a universal asset uploader for not just images like png, jpg etc, but also 3D assets like glb, gltf, and I would like to see a small preview for those too.
I probably need to hook into some javascript function for each @uploads entry.
Any suggestions for where to begin?
1 Like
It’s kind of a workaround but you need to create an input tag separate from your live_file_input and add an event listener to it so you can create a new DOM element and send the file to the server every time someone provides an input, here is my hook responsible for sending content of a selected directory as an example of somewhat similar functionality:
hook = {
mounted() {
this.el.addEventListener("input", (e) => {
e.preventDefault();
Array.from(e.target.files).forEach((file) => {
let relativePath = file.webkitRelativePath
.split("/")
.slice(1)
.join("/");
console.log(relativePath);
let newFile = new File([file], relativePath, { type: file.type });
this.upload("project", [newFile]);
});
});
},
};
In third line there is an event listener added to the input tag and in the 12th line the file is uploaded to the server with “project” title.
For generating a preview you probably want to use three.js or model viewer.
1 Like
Thanks for the suggestion. But I’m confused as to why we would want to upload the file to server every time the input is provided? Isn’t the objective to start uploading the selected files only when the form is submitted? What would be the purpose to pre-upload the staged input files to the server since three.js (or in my case babylon.js) can operate on the client side to render the preview?
1 Like
Both approaches to uploading have their pros and cons.
Uploading every time a file is selected approach(github works like that) is a good choice when you don’t expect user to add&remove files too frequently, this approach is nice because once user clicks “Submit” all files are already on the server so user can interact with web pages related to the uploaded content instantly.
Uploading files after submitting is better when your users add and remove them often as your server won’t have to process any data which is going to be removed anyways, but user might need to wait more time in some scenarios.