IHP 中的檔案上傳在formFor沒有 JS的情況下與formForWithoutJavascript.
我想嘗試在沒有 JS 的情況下執行檔案上傳,因為我認為如果沒有 Turbolinks 和 Morphdom,我的應用程式的某些部分可能會更好。
我創建了一個GitpodFile,通過資料庫中的簡單記錄來演示問題:https : //olive-bonobo-8tmc7rr9.ws-eu25.gitpod.io/
如果效果更好,也可以回購:https : //github.com/kodeFant/file-upload-nojs
在 中Web/View/Files/New.hs,我們有一個帶有檔案上傳和預覽的標準表單,這似乎運作良好。
renderForm :: File -> Html
renderForm file = formForWithoutJavascript file [hsx|
<input
type="file"
name="fileUrl"
class="form-control-file"
accept="image/*"
data-preview="#fileUrlPreview"
/>
<img id="fileUrlPreview"/>
{submitButton}
|]
上傳操作的行為不像我預期的那樣。檔案名保存在記錄中,但沒有路徑。并putStrLn $ show fileUrl列印Nothing,因此檔案本身似乎沒有被拾取。
action CreateFileAction = do
let file = newRecord @File
let fileUrl = fileOrNothing "fileUrl"
putStrLn $ show fileUrl
file
|> buildFile
|> ifValid \case
Left file -> render NewView { .. }
Right file -> do
file <- file |> createRecord
setSuccessMessage "File created"
redirectTo FilesAction
這是否可以在無 js 的形式中修復,還是僅支持 Turbolinks/Morphdom?
uj5u.com熱心網友回復:
如果不對此進行測驗,我認為 JS 和無 JS 版本之間的一個區別是,enctype="multipart/form-data"當檔案輸入存在時,JS 版本會自動設定在表單上。
no JS 解決方案未enctype="multipart/form-data"在表單上使用。因此,檔案使用默認編碼application/x-www-form-urlencoded。該編碼不支持檔案名。因此檔案名為Nothing.
嘗試這樣的事情來驗證這個假設:
renderForm :: File -> Html
renderForm file = [hsx|
<form method="POST" action={CreateFileAction} enctype="multipart/form-data">
<input
type="file"
name="fileUrl"
class="form-control-file"
accept="image/*"
data-preview="#fileUrlPreview"
/>
<img id="fileUrlPreview"/>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
|]
uj5u.com熱心網友回復:
根據 Marc 的有用回答,我可以通過設定如下自定義表單選項來使檔案上傳按預期作業:
customFormOptions :: FormContext File -> FormContext File
customFormOptions formContext =
formContext
|> set #disableJavascriptSubmission True
|> set #customFormAttributes [ ("enctype", "multipart/form-data") ]
然后我可以這樣寫一個表格:
renderForm :: File -> Html
renderForm file = formForWithOptions file customFormOptions [hsx|
<input
type="file"
name="fileUrl"
class="form-control-file"
accept="image/*"
data-preview="#fileUrlPreview"
/>
<img id="fileUrlPreview"/>
{submitButton}
|]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406840.html
標籤:
下一篇:如何在我的玩具語言中正確評估此值
