ファイルアップロード

この例では、プログレスバーを使用した、Ajax経由で送信されるファイルアップロードフォームを作成する方法を説明します。

2 つの異なる実装を紹介します。1 つは純粋な JavaScript(htmx の一部のユーティリティメソッドを使用)、もう 1 つは hyperscript です。

まず、純粋な JavaScript バージョンです。

    <form id='form' hx-encoding='multipart/form-data' hx-post='/upload'>
        <input type='file' name='file'>
        <button>
            Upload
        </button>
        <progress id='progress' value='0' max='100'></progress>
    </form>
    <script>
        htmx.on('#form', 'htmx:xhr:progress', function(evt) {
          htmx.find('#progress').setAttribute('value', evt.detail.loaded/evt.detail.total * 100)
        });
    </script>

Hyperscript バージョンは非常に似ていますが、異なります

    <form hx-encoding='multipart/form-data' hx-post='/upload'
          _='on htmx:xhr:progress(loaded, total) set #progress.value to (loaded/total)*100'>
        <input type='file' name='file'>
        <button>
            Upload
        </button>
        <progress id='progress' value='0' max='100'></progress>
    </form>

hyperscript を使用すると、details のプロパティを直接変数に構造化解除できることに注意してください