pavancse17
LiveView live_file_input with auto_upload + save
Hi Devs,
I am using Uploads — Phoenix LiveView v0.15.4 (hexdocs.pm) feature in my application. I am using it with auto_upload: true option like below:
allow_upload(:excel_file,
accept: ~w(.xlsx),
max_entries: 1,
auto_upload: true,
progress: &handle_progress/3
My requirement is I need to validate the file on fly before submitting the form. I am able to achieve this pretty easily with auto_upload. But I need to save file only after form gets submitted. I am doing it in not so efficient way. My solution for this is as below:
- Validate the file. If the file is valid copy it to temporary folder.
- Upon submitting the form save file to s3 bucket and remove it from temporary folder.
Here if we observe Phoenix live view automatically keeps it in temp folder with auto_upload option. but I am unable to use it on form submit because that live file upload process is deleting it on exiting the process. Is there a way to use the same temp file created by phoenix live view or any other idea which is better than mine
.
Most Liked
aseigo
Assuming you are running this on a UNIX-like OS, if you just move the file to a new filename on the same volume, it won’t copy the data (which is slow) but simply create a new file entry for it (fast), and the Phoenix process will not delete it. I have a function that attempts to move the file, and only if that fails then falls back to copy for this exact purpose:
@doc "Move a file, copy if we must"
@spec move_file(src_path :: String.t(), dest_path :: String.t()) :: :ok | :error
def move_file(src_path, dest_path) do
# move if we can, copy if we have to
case File.rename(src_path, dest_path) do
{:error, :exdev} ->
case File.copy(src_path, dest_path) do
{:error, _} = error -> error
_ -> :ok
end
{:error, _} = error -> error
_ -> :ok
end
end
mcrumm
Correct, the uploaded temp file is cleaned up when its upload process exits, but this does not occur until you invoke one of the consume_uploaded_* functions for a given upload entry. So you can start uploading automatically and still wait to consume them in your form’s phx-submit handler.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









