文件上传

在本示例中,我们展示如何创建一个通过 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 中解构属性到变量