文件上传

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

¥In this example we show how to create a file upload form that will be submitted via ajax, along with a progress bar.

我们将展示两种不同的实现,一种是纯 javascript(使用 htmx 中的一些实用方法),一种是 hyperscript

¥We will show two different implementation, one in pure javascript (using some utility methods in htmx) and one in hyperscript

首先是纯 javascript 版本。

¥First the pure javascript version.

    <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 版本非常相似,除了:

¥The Hyperscript version is very similar, except:

    <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 中的属性直接解构为变量

¥Note that hyperscript allows you to destructure properties from details directly into variables