在这个例子中,我们展示了如何创建一个将通过 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.
我们有一个 multipart/form-data
类型的表单,以便文件能够被正确编码
¥We have a form of type multipart/form-data
so that the file will be properly encoded
我们将表单发布到 /upload
¥We post the form to /upload
我们有一个 progress
元素
¥We have a progress
element
我们监听 htmx:xhr:progress
事件,并根据事件详细信息中的 loaded
和 total
属性更新进度条的 value
属性。
¥We listen for the htmx:xhr:progress
event and update the value
attribute of the progress bar based on the loaded
and total
properties in the event detail.
<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:
脚本直接嵌入在表单元素中
¥The script is embedded directly on the form element
Hyperscript 提供更好的语法(尽管 htmx API 也非常好!)
¥Hyperscript offers nicer syntax (although the htmx API is pretty nice too!)
<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