File upload
A form with a file field, a progress bar that fills while the file is sent, and a message from the server when it arrives.
The page
The progress comes from the browser and needs the ypy-upload extension. Without it the upload still works and the bar
stays empty.
<script src="https://cdn.jsdelivr.net/gh/ypy-develop/[email protected]/dist/ypy.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/ypy-develop/[email protected]/dist/ext/ypy-upload.min.js"></script>
<form ypy-post="/files"
ypy-encoding="multipart/form-data"
ypy-upload-progress="#bar"
ypy-target="#result"
ypy-error-target="#result">
<label>Document <input type="file" name="doc" required></label>
<button>Send</button>
<progress id="bar" max="100" value="0">0%</progress>
</form>
<div id="result" aria-live="polite"></div>What the server answers
The server sees an ordinary multipart/form-data request with one part named doc. It checks the size before it
parses anything, keeps the file under a name of its own (the name the client sent is only shown back) and answers with a
fragment:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Vary: YPY-Request<p>Received quarterly-report-2026-q3.pdf.</p>When something is wrong with the file, it answers 422 with the message, and ypy-error-target puts it in #result:
HTTP/1.1 422 Unprocessable Content
Content-Type: text/html; charset=utf-8
Vary: YPY-Request<p role="alert">The file is larger than 10 MB.</p>| Case | Status | Body |
|---|---|---|
| File stored | 200 |
<p>Received ...</p> |
| No file chosen | 422 |
<p role="alert">Choose a file.</p> |
| File over 10 MB | 422 |
<p role="alert">The file is larger than 10 MB.</p> |
| Storage failed | 500 |
an error message |
How it works
-
ypy-encoding="multipart/form-data"sends the form as multipart, which a file field needs. A form withenctype="multipart/form-data"does the same. -
ypy-upload-progress="#bar"is the switch. A request whose body holds a file that is not empty and whose element has this attribute is sent withXMLHttpRequest, which reports progress.fetchcannot. -
The selector names the element that shows the percentage. A
<progress>getsvalueandmax="100"; any other element gets the CSS variable--ypy-uploadand the attributedata-ypy-upload. Theypy:upload:progressevent carriesloaded,totalandpercentfor your own code. -
The answer goes into
#resultlike any other. Withoutypy-error-target, a422goes into the form, as in forms. -
The server should limit the size before it parses the body. The browser's progress is ahead of what the server has received.
Variations
-
Reset the bar between uploads: the value stays at 100 after a transfer. Listen to
ypy:finally:requestin a script file and setvalueback to 0. -
A bar that is not a
<progress>: give an elementrole="progressbar"and a width ofvar(--ypy-upload, 0%)in your stylesheet. It also getsaria-valuenow. Seeypy-upload. - Keep the file after an error in another field: see preserve file inputs.