文件上传

在这个例子中,我们展示了如何创建一个通过 ajax 提交的文件上传表单,以及一个进度条。

我们将展示两种不同的实现方式,一种是使用纯 javascript(使用 htmx 中的一些实用方法),另一种是使用 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 中解构属性到变量中。