| 1 | --- |
| 2 | includeMockServer: true |
| 3 | title: "File Upload" |
| 4 | description: Upload files with progress and validation |
| 5 | icon: "icon-[mdi--file-upload-outline]" |
| 6 | soon: true |
| 7 | --- |
| 8 | |
| 9 | <script> |
| 10 | function renderForm(errors = {}, values = {}) { |
| 11 | const inputClass = "block w-full px-3 py-2.5 text-sm border rounded-md bg-white dark:bg-neutral-900 text-neutral-800 dark:text-neutral-200 outline-none transition focus:border-neutral-400 dark:focus:border-neutral-500"; |
| 12 | const labelClass = "block text-xs font-medium uppercase tracking-wide text-neutral-500 dark:text-neutral-400 mb-1.5"; |
| 13 | const errorClass = "text-[0.675rem] text-red-600 dark:text-red-400 mt-1.5"; |
| 14 | const border = (field) => errors[field] |
| 15 | ? "border-red-300 dark:border-red-700" |
| 16 | : "border-neutral-200 dark:border-neutral-700"; |
| 17 | |
| 18 | const fileSelected = values.file; |
| 19 | |
| 20 | return ` |
| 21 | <form id="upload-form" hx-post="/submit" hx-target="#upload-wrapper" hx-swap="innerHTML" |
| 22 | hx-on::after-settle="var fi=document.getElementById('file-input'); var lb=document.getElementById('file-label'); if(fi&&lb&&fi.files[0]) lb.textContent=fi.files[0].name" |
| 23 | class="w-full mx-auto flex flex-col gap-5"> |
| 24 | <div class="grid grid-cols-2 gap-4"> |
| 25 | <div> |
| 26 | <label for="name-input" class="${labelClass}">Name</label> |
| 27 | <input id="name-input" name="name" placeholder="Jane Smith" value="${values.name || ''}" |
| 28 | class="${inputClass} ${border('name')}"> |
| 29 | ${errors.name ? '<p class="' + errorClass + '">' + errors.name + '</p>' : ''} |
| 30 | </div> |
| 31 | <div> |
| 32 | <label for="email-input" class="${labelClass}">Email</label> |
| 33 | <input id="email-input" name="email" type="email" placeholder="[email protected]" value="${values.email || ''}" |
| 34 | class="${inputClass} ${border('email')}"> |
| 35 | ${errors.email ? '<p class="' + errorClass + '">' + errors.email + '</p>' : ''} |
| 36 | </div> |
| 37 | </div> |
| 38 | <div> |
| 39 | <label for="file-input" |
| 40 | class="group flex flex-col items-center justify-center gap-2 px-4 py-6 border-2 border-dashed ${errors.file ? 'border-red-300 dark:border-red-700' : 'border-neutral-200 dark:border-neutral-800'} rounded-lg cursor-pointer transition hover:border-neutral-400 dark:hover:border-neutral-500 hover:bg-neutral-50 dark:hover:bg-neutral-850 active:scale-[0.99]"> |
| 41 | <i class="icon-[mdi--cloud-upload-outline] size-8 text-neutral-400 dark:text-neutral-500 group-hover:text-neutral-500 dark:group-hover:text-neutral-400 transition"></i> |
| 42 | <span class="text-sm text-neutral-600 dark:text-neutral-400" id="file-label">${fileSelected ? fileSelected : 'Choose a file'}</span> |
| 43 | </label> |
| 44 | <input hx-preserve id="file-input" type="file" name="file" class="sr-only" |
| 45 | onchange="document.getElementById('file-label').textContent=this.files[0]?.name||'Choose a file'"> |
| 46 | ${errors.file ? '<p class="' + errorClass + '">' + errors.file + '</p>' : ''} |
| 47 | </div> |
| 48 | <button type="submit" |
| 49 | class="w-full px-5 py-2.5 text-sm font-medium rounded-md text-white dark:text-neutral-900 bg-neutral-800 dark:bg-neutral-200 cursor-pointer hover:bg-neutral-700 dark:hover:bg-neutral-300 active:scale-[0.98] transition"> |
| 50 | Submit |
| 51 | </button> |
| 52 | </form>`; |
| 53 | } |
| 54 | |
| 55 | server.get("/demo", () => |
| 56 | `<div id="upload-wrapper" class="starting:opacity-0 transition duration-300">${renderForm()}</div>`); |
| 57 | |
| 58 | server.post("/submit", (req) => { |
| 59 | const name = (req.params.name || '').trim(); |
| 60 | const email = (req.params.email || '').trim(); |
| 61 | const hasFile = req.params.file && req.params.file !== '' && req.params.file !== '[object File]'; |
| 62 | |
| 63 | const errors = {}; |
| 64 | if (!name) errors.name = 'Name is required.'; |
| 65 | if (!email) errors.email = 'Email is required.'; |
| 66 | else if (!email.includes('@')) errors.email = 'Enter a valid email.'; |
| 67 | |
| 68 | if (Object.keys(errors).length > 0) { |
| 69 | return renderForm(errors, { name, email, file: hasFile ? 'file' : '' }); |
| 70 | } |
| 71 | |
| 72 | return ` |
| 73 | <div class="w-full max-w-sm mx-auto starting:opacity-0 transition duration-300"> |
| 74 | <div class="flex flex-col items-center gap-3 py-8 text-center"> |
| 75 | <i class="icon-[mdi--check-circle] size-12 text-green-500 dark:text-green-400"></i> |
| 76 | <p class="text-sm font-medium text-neutral-800 dark:text-neutral-200">Submitted successfully</p> |
| 77 | <p class="text-xs text-neutral-500 dark:text-neutral-400">Your file selection was preserved through validation.</p> |
| 78 | <button hx-get="/reset" hx-target="#upload-wrapper" hx-swap="innerHTML" |
| 79 | class="mt-2 px-4 py-2 text-[0.8125rem] font-medium text-neutral-600 dark:text-neutral-400 hover:text-neutral-800 dark:hover:text-neutral-200 hover:bg-neutral-50 dark:hover:bg-neutral-850 rounded-md cursor-pointer transition active:scale-[0.98]"> |
| 80 | Try again |
| 81 | </button> |
| 82 | </div> |
| 83 | </div>`; |
| 84 | }); |
| 85 | |
| 86 | server.get("/reset", () => renderForm()); |
| 87 | |
| 88 | server.start("/demo"); |
| 89 | </script> |
| 90 | |
| 91 | <div id="demo-content" class="not-prose demo-container flex items-center justify-center min-h-[460px]"></div> |
| 92 | |
| 93 | ## Basic usage |
| 94 | |
| 95 | On the client, set `hx-encoding` to `multipart/form-data`: |
| 96 | |
| 97 | ```html |
| 98 | <form hx-post="/upload" |
| 99 | hx-encoding="multipart/form-data"> |
| 100 | <input type="file" name="file"> |
| 101 | <input type="text" name="name"> |
| 102 | <button>Submit</button> |
| 103 | </form> |
| 104 | ``` |
| 105 | |
| 106 | - [`hx-encoding`](/reference/attributes/hx-encoding)=`"multipart/form-data"` sends the form as [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData), required for file uploads. |
| 107 | - [`hx-post`](/reference/attributes/hx-post) submits the form to `/upload`. |
| 108 | |
| 109 | On the server, respond with a success or error message: |
| 110 | |
| 111 | ```html |
| 112 | <p>File uploaded successfully.</p> |
| 113 | ``` |
| 114 | |
| 115 | ## Preserving file selection on errors |
| 116 | |
| 117 | When a form re-renders with validation errors, file inputs lose their selection. Add [`hx-preserve`](/reference/attributes/hx-preserve) to keep it: |
| 118 | |
| 119 | ```html |
| 120 | <form hx-post="..." |
| 121 | hx-swap="outerHTML" |
| 122 | hx-encoding="multipart/form-data"> |
| 123 | <input hx-preserve type="file" name="file"> |
| 124 | <input type="text" name="name"> |
| 125 | <button>Submit</button> |
| 126 | </form> |
| 127 | ``` |
| 128 | |
| 129 | Try it in the demo: select a file, then submit with empty fields. The form re-renders with errors, but your file selection stays. |
| 130 | |
| 131 | Alternatively, place the file input outside the swap target using the [`form` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form): |
| 132 | |
| 133 | ```html |
| 134 | <input form="my-form" type="file" name="file"> |
| 135 | |
| 136 | <form id="my-form" hx-post="..." |
| 137 | hx-encoding="multipart/form-data"> |
| 138 | <button>Submit</button> |
| 139 | </form> |
| 140 | ``` |
| 141 | |
| 142 | The input is outside the form element, so it is never replaced during swaps. |
| 143 | |
| 144 | ## Upload progress |
| 145 | |
| 146 | htmx 4.x uses the native [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API. `fetch` supports [upload progress monitoring](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#monitoring_upload_progress) in some browsers, but cross-browser support is limited. For reliable progress tracking, use [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload) directly: |
| 147 | |
| 148 | ```html |
| 149 | <form id="upload-form" enctype="multipart/form-data"> |
| 150 | <input type="file" name="file"> |
| 151 | <button>Upload</button> |
| 152 | <progress id="progress" value="0" max="100"></progress> |
| 153 | </form> |
| 154 | |
| 155 | <script> |
| 156 | document.querySelector('#upload-form').addEventListener('submit', (e) => { |
| 157 | e.preventDefault(); |
| 158 | const xhr = new XMLHttpRequest(); |
| 159 | xhr.upload.addEventListener('progress', (evt) => { |
| 160 | document.querySelector('#progress').value = (evt.loaded / evt.total) * 100; |
| 161 | }); |
| 162 | xhr.open('POST', '/upload'); |
| 163 | xhr.send(new FormData(e.target)); |
| 164 | }); |
| 165 | </script> |
| 166 | ``` |