htmx icon indicating copy to clipboard operation
htmx copied to clipboard

form submission without a file selected

Open maxwellt opened this issue 2 years ago • 1 comments

I've noticed a discrepancy in how forms behave when using HTMX compared to standard HTML forms. Specifically, this difference arises with file input elements. In a standard HTML form, if a file input element is left empty and the form is submitted, the input's name attribute still appears in the HTTP request's body. However, with HTMX, the name attribute doesn't show up in the body of the HTTP request if no file is selected.

Here's an example to illustrate:

Standard HTML Form Example:

<form action="add" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Submit">
</form>

In this case, submitting the form without selecting a file results in the HTTP body including the 'file' attribute name but no binary data:

-----------------------------10335236603037115181545093065
Content-Disposition: form-data; name="file"; filename=""
Content-Type: application/octet-stream

-----------------------------10335236603037115181545093065--

HTMX Form Example:

    <form hx-post="add" hx-encoding="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit" value="Submit">
    </form>

Here, submitting the form without a file selection results in an empty HTTP body.

The issue seems to be resolved by checking for an empty array if (Array.isArray(value) && value.length) in the makeFormData function within htmx.js.

maxwellt avatar Dec 28 '23 16:12 maxwellt

in current version 2.0.3 it not work. The key "file" is missing when sending the request

neznaika0 avatar Nov 06 '24 07:11 neznaika0