表单错误后保留文件输入

当使用包含原始值和文件输入的表单进行服务器端错误处理和验证时,当表单返回错误消息时,文件输入的值将丢失。因此,用户需要重新上传文件,从而导致用户体验不佳。

¥When using server-side error handling and validation with forms that include both primitive values and file inputs, the file input’s value is lost when the form returns with error messages. Consequently, users are required to re-upload the file, resulting in a less user-friendly experience.

为了解决丢失文件输入值的问题,你可以在 input 元素上使用 hx-preserve 属性:

¥To overcome the problem of losing the file input value, you can use the hx-preserve attribute on the input element:

<form method="POST" id="binaryForm" enctype="multipart/form-data" hx-swap="outerHTML" hx-target="#binaryForm">
    <input hx-preserve id="someId" type="file" name="binaryFile">
    <!-- Other code here, such as input error handling. -->
    <button type="submit">Submit</button>
</form>

如果文件字段返回错误,则只要 hx-preserve 仅放置在 input 中,而不是显示错误的元素(例如 ol.errorlist),就会显示这些错误。如果在特定情况下,你希望文件上传输入返回而不保留用户选择的文件(例如,因为文件类型无效),你可以在服务器端管理该问题,方法是在字段出现相关错误时省略 hx-preserve 属性。

¥If the file field is returned with errors on it, they will be displayed provided that hx-preserve was placed in the input only and not the element that would show the errors (e.g. ol.errorlist). If in a given circumstance you want the file upload input to return without preserving the user’s chosen file (for example, because the file was an invalid type), you can manage that on the server side by omitting the hx-preserve attribute when the field has the relevant errors.

或者,你可以通过重组表单来保留表单错误后的文件输入,以便文件输入位于将要交换的区域之外。

¥Alternatively, you can preserve file inputs after form errors by restructuring the form so that the file input is located outside the area that will be swapped.

之前:

¥Before:

<form method="POST" id="binaryForm" enctype="multipart/form-data" hx-swap="outerHTML" hx-target="#binaryForm">
    <input type="file" name="binaryFile">
    <button type="submit">Submit</button>
</form>

之后:

¥After:

<input form="binaryForm" type="file" name="binaryFile">

<form method="POST" id="binaryForm" enctype="multipart/form-data" hx-swap="outerHTML" hx-target="#binaryForm">
    <button type="submit">Submit</button>
</form>
  1. 表单重构:将二进制文件输入移到 HTML 结构中的主表单元素之外。

    ¥Form Restructuring: Move the binary file input outside the main form element in the HTML structure.

  2. 使用表单属性:通过添加表单属性并将其值设置为主表单的 ID 来增强二进制文件输入。此链接将二进制文件输入与表单关联,即使它位于表单元素之外。

    ¥Using the form Attribute: Enhance the binary file input by adding the form attribute and setting its value to the ID of the main form. This linkage associates the binary file input with the form, even when it resides outside the form element.