Skip to content

Commit a1b44df

Browse files
authored
Merge pull request #7090 from QwikDev/pr-dynamic-action-file-upload
docs: added file upload example
2 parents 704fbae + 11e391d commit a1b44df

File tree

1 file changed

+49
-0
lines changed
  • packages/docs/src/routes/docs/(qwikcity)/action

1 file changed

+49
-0
lines changed

packages/docs/src/routes/docs/(qwikcity)/action/index.mdx

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ contributors:
2525
- gioboa
2626
- jemsco
2727
- tzdesign
28+
- shairez
2829
updated_at: '2023-12-15T11:00:00Z'
2930
created_at: '2023-03-20T23:45:13Z'
3031
---
@@ -145,6 +146,54 @@ export default component$(() => {
145146

146147
In the example above, the `addUser` action is triggered when the user clicks the button. The `action.submit()` method returns a `Promise` that resolves when the action is done.
147148

149+
### Uploading files
150+
151+
When using `<Form>` with a file input, the submission will be sent as a `multipart/form-data` request.
152+
153+
But when using actions programmatically, you can still upload files by passing a `File` object to the `action.submit()` method by creating a `FormData` object and appending the file to it.
154+
155+
```tsx title="src/routes/index.tsx"
156+
157+
import { component$ } from '@builder.io/qwik';
158+
import { routeAction$ } from '@builder.io/qwik-city';
159+
160+
export const useUploadFile = routeAction$(async ({file}) => {
161+
// save the file somewhere...
162+
return {
163+
success: true,
164+
};
165+
});
166+
167+
export default component$(() => {
168+
const action = useUploadFile();
169+
const fileUploadRef = useSignal<HTMLInputElement | undefined>();
170+
return (
171+
<section>
172+
<input type="file" ref={fileUploadRef}/>
173+
<button
174+
onClick$={async () => {
175+
176+
const file = fileUploadRef.value?.files?.[0];
177+
178+
if (file){
179+
const formData = new FormData();
180+
formData.append('file', file);
181+
const { value } = await action.submit(formData);
182+
console.log(value);
183+
}
184+
}}
185+
>
186+
Upload file
187+
</button>
188+
189+
</section>
190+
);
191+
});
192+
193+
```
194+
195+
196+
148197
## Actions with Event Handlers
149198

150199
The `onSubmitCompleted$` event handler can be used after an action is successfully executed and returns some data. This is useful for performing tasks, such as resetting UI elements or updating the application state, once an action has been completed.

0 commit comments

Comments
 (0)