Skip to content

Commit

Permalink
Merge pull request #1075 from Zerotask/patch-1
Browse files Browse the repository at this point in the history
docs(file-uploads): minor adjustments
  • Loading branch information
vitalik authored Feb 9, 2024
2 parents bc90e94 + a4c6801 commit 08af4b9
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions docs/docs/guides/input/file-params.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ def upload(request, file: UploadedFile = File(...)):
- name
- size
- content_type
- content_type_extra
- charset
- etc.

## Uploading array of files

To **upload several files** at the same time, just declare a `List` of `UploadFile`:
To **upload several files** at the same time, just declare a `List` of `UploadedFile`:


```python hl_lines="1 6"
Expand All @@ -40,9 +42,9 @@ def upload_many(request, files: List[UploadedFile] = File(...)):

## Uploading files with extra fields

Note: HTTP protocol does not allow you to send files in application/json format by default (unless you encode it somehow to JSON on client side)
Note: The HTTP protocol does not allow you to send files in `application/json` format by default (unless you encode it somehow to JSON on client side)

To send files along with some extra attributes you need to send bodies in multipart/form-data encoding. You can do it by simply marking fields with `Form`:
To send files along with some extra attributes, you need to send bodies with `multipart/form-data` encoding. You can do it by simply marking fields with `Form`:

```python hl_lines="14"
from ninja import NinjaAPI, Schema, UploadedFile, Form, File
Expand All @@ -57,7 +59,7 @@ class UserDetails(Schema):
birthdate: date


@api.post('/user')
@api.post('/users')
def create_user(request, details: Form[UserDetails], file: File[UploadedFile]):
return [details.dict(), file.name]

Expand All @@ -68,22 +70,22 @@ Note: in this case all fields should be send as form fields
You can as well send payload in single field as JSON - just remove the Form mark from:

```python
@api.post('/user')
@api.post('/users')
def create_user(request, details: UserDetails, file: File[UploadedFile]):
return [details.dict(), file.name]

```

this will expect from client side to send data as multipart/form-data with 2 fields:
this will expect from the client side to send data as `multipart/form-data with 2 fields:

- details: Json as string
- details: JSON as string
- file: file


### List of files with extra info

```python
@api.post('/user')
@api.post('/users')
def create_user(request, details: Form[UserDetails], files: File[list[UploadedFile]]):
return [details.dict(), [f.name for f in files]]
```

0 comments on commit 08af4b9

Please sign in to comment.