# File Uploads
> Let visitors upload files from a Widget straight to your own endpoint, then use the uploaded file's URL in the Widget.
A Widget can take files from the visitor and send them to an endpoint you control. QwryAI never stores or passes on the file. The visitor's browser sends each file straight to your URL as a `multipart/form-data` request, and the Widget saves the URL your endpoint returns, so you can show it or pass it to another function.
Two pieces work together:
* An **Upload file** function that holds your endpoint, the file limits and what happens after each file. Set it up in the **Functions** tab. See [Functions](/docs/developer-guides/widgets/functions#function-types).
* A `Button` in the Widget code that runs the function. Clicking it opens the visitor's file picker.
## Set Up an Upload
**1. Add a button to the code**
Point the button's `onClickAction` at the function you'll create next, and show the uploaded file with a variable.
```jsx
{photoUrl && }
```
Add `photoUrl` to the Widget's [schema](/docs/developer-guides/widgets/code-editor#schema) as an optional string.
**2. Create the function**
In the **Functions** tab, click **Add function**, name it `uploadPhoto` and set its **Function type** to **Upload file**. Enter your URL under **Endpoint** and choose `POST` or `PUT`. Set **Target field** to `photoUrl`, and **URL field** to the path in your JSON response that holds the file's URL, for example `data.url`.


**3. Allow the request on your server**
Your endpoint must accept multipart uploads and allow cross-origin requests (CORS) from `https://www.qwryai.com`. The Widget runs inside QwryAI's chat window, so that's the request's origin wherever your site shows the agent. It's also where the builder preview runs. See [Your Endpoint](#your-endpoint).
**4. Try it in the preview**
Click the button in the preview and pick a file. Uploads in the builder go to your real endpoint with the function's current settings, so you can check success and failure before you save.
## How an Upload Runs
1. The visitor clicks the button and picks files. The picker only offers the **Accepted types**, and allows several files only when **Allow multiple** is on.
2. Each file is checked against **Max size (MB)** and **Accepted types**. A file that fails isn't sent, and **On failure (per file)** runs with the reason in `{{file.error}}`, such as `File type is not accepted.` or `File exceeds 10 MB.` Picking more than **Max files** fails the whole upload with `Choose at most 5 files.`
3. **On start** runs once, then the files are sent one at a time, each in its own request.
4. A `2xx` response marks the file as uploaded. The Widget reads the URL from the JSON body at **URL field** and saves it in **Target field**. Any **Return schema** fields are saved into Widget variables too. Then **On success (per file)** runs.
5. Any other response marks the file as failed, with `{{file.error}}` set to `Upload failed ().`, for example `Upload failed (500).` Then **On failure (per file)** runs. The response body is never shown to the visitor.
> [!WARNING]
>
> Your endpoint must answer with a JSON body. If **URL field** is empty, or the response has no text at that path, the upload still counts as a success, but `{{file.url}}` and **Target field** are left empty.
## Your Endpoint
Each request is a `multipart/form-data` `POST` or `PUT` containing:
* The file, under the field name in **File field**. The default is `file`. The original filename is kept.
* Any **Form fields** you set, after the file.
* Your **Headers** and **Query params**, with [template tokens](/docs/developer-guides/widgets/functions#template-tokens) filled in.
Don't set a `Content-Type` header. The browser sets it so the multipart boundary is right, and the builder won't save a function that has one.
Tokens available in the endpoint, query parameters and form fields: every Widget variable, any [additional inputs](/docs/developer-guides/widgets/functions#additional-inputs), `{{conversationId}}`, `{{widgetId}}`, and `{{file.name}}`, `{{file.size}}` and `{{file.type}}` for the file being sent.
A minimal Express endpoint:
```js
import cors from "cors";
import express from "express";
import multer from "multer";
const upload = multer({ limits: { fileSize: 30 * 1024 * 1024 } });
const app = express();
app.use(cors({ origin: ["https://www.qwryai.com"] }));
app.post("/uploads", upload.single("file"), async (req, res) => {
const url = await storeSomewhere(req.file);
res.json({ url });
});
```
With that response, set **URL field** to `url`.
## Use the Uploaded Files
The uploaded file's URL is saved in the variable named in **Target field**. With **Allow multiple** on, that variable holds a list of URLs, one for each file uploaded so far.
```json
{
"photoUrl": "https://files.example.com/damage-1.jpg"
}
```
Some ways to use it:
* Show the image: ``. With **Allow multiple**, loop over the list with `.map()`.
* Copy details into other variables with an **On success (per file)** follow-up of type **Set variables**, for example set `fileName` to `{{file.name}}`.
* Show a state only after an upload, with a [state condition](/docs/developer-guides/widgets/states) such as `photoUrl` **is not empty**.
* Send the URL to another API with a **Call API** function whose body uses `{{photoUrl}}`.
In the per-file follow-ups, `{{file.url}}`, `{{file.name}}`, `{{file.size}}`, `{{file.type}}`, `{{file.error}}` and every **Return schema** field are available.
> [!NOTE]
>
> Uploaded file URLs and return fields are saved with the Widget in the conversation. Return URLs you're happy to keep there. A short-lived signed URL stops working in the conversation history once it expires.
## Limits
| Limit | Value |
| - | - |
| Maximum file size | 30 MB per file, whatever **Max size (MB)** says. |
| Maximum files per upload | 5, whatever **Max files** says. 1 unless **Allow multiple** is on. |
| Files sent at once | 1. Files are sent one after another. |
| Methods | `POST` or `PUT`. |
| URL | Must start with `https://`. |
> [!NOTE]
>
> The size and type checks run in the browser before anything is sent. Your endpoint should enforce its own limits too.
## Secure Your Endpoint
The upload request comes from the visitor's browser, not from QwryAI. Anyone who can open your chat can find the URL and send requests to it, so treat it as a public endpoint.
> [accordion] Rate limit it
>
> Limit requests per client, and answer `429 Too Many Requests` when the limit is hit. The visitor sees the failure through your **On failure (per file)** follow-up.
>
> Two keys work well together. The limiter runs after the multipart parser, so the form field is available:
>
> * **Per IP**, to stop simple floods.
> * **Per conversation**, so one visitor can't use up the limit for everyone on the same network. Add a **Form field** such as `conversationId` = `{{conversationId}}` and key the limit on it. Each upload sends at most 5 files, so a real visitor rarely sends more than a handful of requests per conversation.
>
> ```js
> import rateLimit from "express-rate-limit";
>
> const uploadLimiter = rateLimit({
> windowMs: 60 * 1000,
> limit: 10,
> keyGenerator: (req) => req.body?.conversationId || req.ip,
> message: "Too Many Requests",
> });
>
> app.post("/uploads", upload.single("file"), uploadLimiter, handler);
> ```
> [accordion] Never put a secret in the headers
>
> Header and query values are sent from the browser, so visitors can read them. Use a public, limited key, or hand out a short-lived token:
>
> 1. Add a **Call API** function that asks your API for an upload token, with `uploadToken` in its **Return schema** so the token is saved as a Widget variable.
> 2. Use it in the upload function's **Headers** as `Bearer {{uploadToken}}`.
> 3. Make the token expire after a few minutes and accept only uploads.
> [accordion] Validate on the server, not just in the Widget
>
> **Accepted types** and **Max size (MB)** are checked in the browser and are easy to get around. On your server, check the size again, detect the file type from its content rather than its name or the request's `Content-Type`, and reject anything you don't expect with a `4xx`.
> [accordion] Restrict CORS to the origins you use
>
> Allow only `https://www.qwryai.com`. The request never comes from the site that shows the chat, because the Widget runs inside QwryAI's chat window. Avoid `Access-Control-Allow-Origin: *` on an endpoint that accepts writes, and answer `OPTIONS` preflight requests with the method and headers you actually use.
> [accordion] Store files outside your web root
>
> Save uploads to object storage or a dedicated bucket, make up your own filenames instead of trusting the visitor's, and return a URL from there. If visitors can upload any file type, scan files for malware before making the URL public.
## Next steps
> [card] Functions | /docs/developer-guides/widgets/functions | Every setting of the Upload file function.
> [card] States | /docs/developer-guides/widgets/states | Show a view once the upload finishes.