檢視原始碼 Phoenix.LiveView.UploadWriter 行為 (Phoenix LiveView v0.20.17)
提供處理上傳區段的行為,將其寫入最終目的地。
預設情況下,上傳會寫入至伺服器上的暫存檔案,而 LiveView 透過讀取暫存檔案或將其複製至耐用的位置來使用。有些用例需要自訂處理上傳的區段,例如將使用者的上傳串流至另一部伺服器。在這種情況下,我們不希望區段寫入磁碟,因為我們只需要將其轉發即可。
注意:區塊上傳函式會在頻道上傳程序中執行,因此任何封鎖工作都會封鎖頻道,錯誤將導致頻道程序崩潰。
可以將 Phoenix.LiveView.UploadWriter
自訂實作傳遞至 allow_upload/3
。若要使用選項初始化上傳函式,請定義一個 3 元函式,它回傳 {writer, writer_opts}
的元組。例如,假設一個上傳函式會記錄區段大小,並追蹤用戶端傳送的總位元組數
socket
|> allow_upload(:avatar,
accept: :any,
writer: fn _name, _entry, _socket -> {EchoWriter, level: :debug} end
)
這樣的 EchoWriter
可以如下所示
defmodule EchoWriter do
@behaviour Phoenix.LiveView.UploadWriter
require Logger
@impl true
def init(opts) do
{:ok, %{total: 0, level: Keyword.fetch!(opts, :level)}}
end
@impl true
def meta(state), do: %{level: state.level}
@impl true
def write_chunk(data, state) do
size = byte_size(data)
Logger.log(state.level, "received chunk of #{size} bytes")
{:ok, %{state | total: state.total + size}}
end
@impl true
def close(state, reason) do
Logger.log(state.level, "closing upload after #{state.total} bytes}, #{inspect(reason)}")
{:ok, state}
end
end
當 LiveView 使用上傳的項目時,它會接收到由 meta 回呼傳回的 %{level: ...}
。這允許上傳函式在其處理區段並稍後在使用時傳遞至 LiveView 時,保留狀態。
關閉原因
close/2
回呼會在上傳完成或取消時呼叫。可以傳遞下列值
:done
- 用戶端已傳送所有預期的區段,而上傳處於等待中的狀態:cancel
- 上傳已取消,原因可能是伺服器或用戶端導覽至其他頁面。{:error, reason}
- 由於write_chunk/2
傳回錯誤,上傳已取消。例如,如果 Ifwrite_chunk/2
傳回{:error, :enoent, state}
,上傳會取消,而close/2
會呼叫原因{:error, :enoent}
。