# Working with files
Source: https://sovaria.in/docs/storage-files

Paths and folders, uploading (and replacing), large files with resumable uploads, listing, moving and renaming, downloading and deleting, and the limits that apply.

## Paths and folders

A file is addressed by its bucket and a path: `avatars` + `6e19…/photo.png`. Folders are just the parts of the path before the last `/`; they exist as long as something is in them (**New folder** in the console creates an empty placeholder). Use the user's id as the first folder for per-user files — the **own folder** rules check exactly that ([Access, links and delivery](https://sovaria.in/docs/storage-access)).

Keep names URL-safe (letters, digits, `-`, `_`, `.`, `/`); the SDKs encode anything else.

## Upload

JavaScript:
```js
const user = await sovaria.auth.me()
await sovaria.storage.upload('avatars', `${user.id}/photo.png`, file, {
  contentType: 'image/png',
  upsert: true,          // replace the file if it exists
})
```

cURL:
```bash
curl -s -X POST "$URL/api/v1/store/objects/avatars/$USER_ID/photo.png?upsert=true" \
  -H "Authorization: Bearer $TOKEN" -F file=@photo.png
```

CLI:
```bash
sov storage upload avatars ./photo.png --name <user-id>/photo.png
```

Or one bucket at a time, as in supabase-js: every call resolves to `{ data, error }` and never throws (except `getPublicUrl`, which needs the project id — known once the client has looked it up, or after `await sovaria.resolveScope()`). In the Swift, Kotlin and Dart SDKs `storage` is where the session is kept, so buckets are `sovaria.files.from(…)`.

JavaScript:
```js
const avatars = sovaria.storage.from('avatars')
const { data, error } = await avatars.upload(`${user.id}/photo.png`, file, { upsert: true })
const { data: blob } = await avatars.download(`${user.id}/photo.png`)
const { data: files } = await avatars.list(user.id, { limit: 50, search: 'photo' })   // names relative to the folder
await avatars.remove([`${user.id}/old.png`])
const { data: { signedUrl } } = await avatars.createSignedUrl(`${user.id}/photo.png`, 3600)
const { data: { publicUrl } } = sovaria.storage.from('public-images').getPublicUrl('logo.png')
```

Python:
```python
avatars = sovaria.storage.from_("avatars")
await avatars.upload(f"{user_id}/photo.png", png_bytes, {"content-type": "image/png", "upsert": "true"})
files = await avatars.list(user_id, {"limit": 50})
url = (await avatars.create_signed_url(f"{user_id}/photo.png", 3600))["signedURL"]
```

Swift:
```swift
let avatars = sovaria.files.from("avatars")
try await avatars.upload("\(userId)/photo.png", data: png, contentType: "image/png", upsert: true)
let url = try await avatars.createSignedURL(path: "\(userId)/photo.png", expiresIn: 3600)
```

Kotlin:
```kotlin
val avatars = sovaria.files.from("avatars")
avatars.upload("$userId/photo.png", png, contentType = "image/png", upsert = true)
val url = avatars.createSignedUrl("$userId/photo.png", 3600)
```

Dart:
```dart
final avatars = sovaria.files.from('avatars');
await avatars.upload('$userId/photo.png', png, contentType: 'image/png', upsert: true);
final url = await avatars.createSignedUrl('$userId/photo.png', 3600);
```

| Situation | Result |
|---|---|
| The path is new | The file is stored. |
| The path exists, without `upsert` | `409 Object … already exists` — nothing is overwritten. |
| The path exists, with `upsert: true` | The file is replaced. There is no version history for files. |
| Bigger than the bucket's or plan's largest file | `413`. |
| Type not in the bucket's allowed types | Refused. |
| The project's storage is full | `403` with a plan code (Free stops; paid plans bill beyond — [Billing, invoices and overage](https://sovaria.in/docs/billing)). |

For browser uploads straight to Sovaria without passing through your server, create a **signed upload URL** on your server and let the browser `PUT` the file to it ([Access, links and delivery](https://sovaria.in/docs/storage-access)).

## Large files: resumable uploads

For files of tens of megabytes or more, or unreliable networks, upload in chunks and resume after a failure. The TypeScript and Python SDKs do the whole protocol for you: they send 6 MB chunks (at least 256 KB), report progress with the upload's id, and given that id later carry on from the offset the server already has.

TypeScript:
```ts
const bucket = sovaria.storage.from('videos')

const { data, error } = await bucket.uploadResumable(`${userId}/clip.mp4`, file, {
  contentType: 'video/mp4',
  onProgress: ({ uploadId, sent, total }) => {
    localStorage.setItem('clip-upload', uploadId)      // keep it to resume later
    setProgress(sent / total)
  },
})

// After a dropped connection or a reload: continue where the server stopped
await bucket.uploadResumable(`${userId}/clip.mp4`, file, { uploadId: localStorage.getItem('clip-upload') ?? undefined })
```

Python:
```python
bucket = sovaria.storage.from_("videos")

out = await bucket.upload_resumable(f"{user_id}/clip.mp4", data, content_type="video/mp4",
                                    on_progress=lambda p: print(p["sent"], "of", p["total"]))
# out == {"path": ..., "full_path": "videos/...", "upload_id": ...}

# Resume an earlier upload from the server's offset
await bucket.upload_resumable(f"{user_id}/clip.mp4", data, upload_id=out["upload_id"])
```

Without an SDK, use the protocol directly (TUS-style):

1. **Start** — Returns `201` with a `Location` header for the upload.
```bash
curl -si -X POST "$URL/api/v1/store/resumable/videos/$USER_ID/clip.mp4" \
  -H "Authorization: Bearer $TOKEN" -H "Upload-Length: 734003200"
# Location: /api/v1/store/resumable/<upload-id>   Upload-Offset: 0
```
2. **Send chunks** — Each `PATCH` carries the offset it starts at; a wrong offset is refused so chunks can't be appended twice.
```bash
curl -s -X PATCH "$URL/api/v1/store/resumable/<upload-id>" \
  -H "Authorization: Bearer $TOKEN" -H "Upload-Offset: 0" \
  -H 'Content-Type: application/offset+octet-stream' --data-binary @chunk-0
```
3. **Resume after a failure** — `HEAD` the upload to read `Upload-Offset`, then continue from there.
4. **Finish** — Send the last chunk with `X-Upload-Complete: 1`; the file appears in the bucket.

An unfinished upload survives server restarts and can be continued from any device. It expires after **24 hours without a chunk**, and its chunks count toward your storage until it finishes or expires. A project can keep up to 20 unfinished uploads at once.

The [S3-compatible storage access](https://sovaria.in/docs/storage-s3) API also supports multipart uploads, so `aws s3 cp`, `rclone` and S3 libraries handle large files for you.

## Malware scanning

Uploads can be checked for malware before they are stored (ClamAV; Sovaria turns it on for the platform). It covers every way in — the SDK and console, signed upload URLs, resumable uploads and the S3 API. A file found to be malware is **refused** and never reaches your bucket:

Response:
```json
HTTP 422
{ "detail": { "code": "MALWARE_DETECTED", "signature": "Win.Trojan.Agent-…",
  "message": "This file was refused: the virus scanner found Win.Trojan.Agent-…. It was not stored." } }
```

- Show the message to the user; retrying the same file gives the same answer. The S3 API answers `403 AccessDenied` with the same reason.
- The refused file is kept for 30 days in a quarantine only Sovaria staff can open (for false-positive review), never in your bucket, and your project's audit log records it (`object.malware_refused`).
- Very large files (over the platform's scan limit, 25 MB by default) are stored without a scan, so keep your own checks for big uploads you don't trust.
- If the scanner is briefly unavailable, uploads are stored as usual (or, if the platform is set to be strict, refused with `503 SCANNER_UNAVAILABLE` — retry shortly).

## List, move, rename, delete

JavaScript:
```js
const files = await sovaria.storage.listObjects('avatars', { prefix: `${user.id}/` })

// Move or rename (both paths are bucket/path)
await sovaria.storage.moveObject({ from_path: `avatars/${user.id}/old.png`, to_path: `avatars/${user.id}/new.png` })

await sovaria.storage.remove('avatars', `${user.id}/new.png`)
```

- Listing returns each file's path, size, content type and last change.
- A move needs `READ` and `DELETE` on the old path and `WRITE` on the new one (it reads the file and removes the original).
- Deleting is immediate and permanent — there is no trash. Deleting a bucket deletes every file in it.

## Copy, details and exists

`copy` duplicates a file inside a bucket or into another one: it needs `READ` on the source and `WRITE` on the destination path, and the copy meets the destination bucket's type and size rules and your storage quota, like an upload of the same file. Without `upsert` an existing file at the destination is a `409`. `info` returns a file's size, content type, cache control, etag and dates without downloading it; `exists` is `info` that answers true or false (a file this user can't read is "not there").

TypeScript:
```ts
const docs = sovaria.storage.from('docs')
await docs.copy(`${user.id}/draft.pdf`, `${user.id}/final.pdf`)
await docs.copy(`${user.id}/final.pdf`, `${user.id}/final.pdf`, { destinationBucket: 'archive' })
await docs.move(`${user.id}/old.pdf`, `${user.id}/2025/old.pdf`)
const { data: info } = await docs.info(`${user.id}/final.pdf`)   // size, content_type, cache_control, etag, updated_at
const { data: there } = await docs.exists(`${user.id}/final.pdf`)
```

Python:
```python
docs = sovaria.storage.from_("docs")
await docs.copy(f"{user_id}/draft.pdf", f"{user_id}/final.pdf")
info = await docs.info(f"{user_id}/final.pdf")
there = await docs.exists(f"{user_id}/final.pdf")
```

Swift:
```swift
let docs = sovaria.files.from("docs")
try await docs.copy(from: "\(userId)/draft.pdf", to: "\(userId)/final.pdf")
let info = try await docs.info(path: "\(userId)/final.pdf")
let there = try await docs.exists(path: "\(userId)/final.pdf")
```

Kotlin:
```kotlin
val docs = sovaria.files.from("docs")
docs.copy("$userId/draft.pdf", "$userId/final.pdf")
val info = docs.info("$userId/final.pdf")
val there = docs.exists("$userId/final.pdf")
```

Dart:
```dart
final docs = sovaria.files.from('docs');
await docs.copy('$userId/draft.pdf', '$userId/final.pdf');
final info = await docs.info('$userId/final.pdf');
final there = await docs.exists('$userId/final.pdf');
```

## Cache control

Pass `cacheControl` (seconds, e.g. `'3600'`) when uploading to tell browsers and CDNs how long they may keep the file: it is stored with the file and sent back as `Cache-Control` on downloads, public URLs and transformed images (up to one year; anything but a number of seconds is a `400`). Without it, public files are cached for 5 minutes and other downloads aren't cached.

TypeScript:
```ts
await sovaria.storage.from('assets').upload('logo.svg', file, { cacheControl: '86400', upsert: true })
```

Python:
```python
await sovaria.storage.from_("assets").upload("logo.svg", data, {"cache-control": "86400", "upsert": "true"})
```

Swift:
```swift
try await sovaria.files.from("assets").upload("logo.svg", data: svg, contentType: "image/svg+xml", upsert: true, cacheControl: "86400")
```

Kotlin:
```kotlin
sovaria.files.from("assets").upload("logo.svg", svg, "image/svg+xml", upsert = true, cacheControl = "86400")
```

Dart:
```dart
await sovaria.files.from('assets').upload('logo.svg', svg, upsert: true, cacheControl: '86400');
```

cURL:
```bash
curl -s -X POST "$URL/api/v1/store/objects/assets/logo.svg?upsert=true" \
  -H "Authorization: Bearer $TOKEN" -F cacheControl=86400 -F file=@logo.svg
```

## Download

`sovaria.storage.download(bucket, path)` returns a `Blob` for the signed-in user. For `<img>` tags and links, use a public URL (public buckets) or a signed URL (private ones) instead of downloading in JavaScript — [Access, links and delivery](https://sovaria.in/docs/storage-access).

## Limits

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Object storage | 1 GB | 20 GB | 100 GB | 500 GB | 5 TB |
| Files | 100 MB | 2 GB | 10 GB | 50 GB | 100 GB |
| Buckets | 3 | 100 | 500 | 2,000 | 10,000 |
| Monthly bandwidth | 2,147,483,648 | 21,474,836,480 | 64,424,509,440 | 429,496,729,600 | 5,497,558,138,880 |

A bucket can set a lower largest-file size and a list of allowed content types (Bucket › Settings, or `file_size_limit` / `allowed_mime_types` when creating it).
