# Uploading a file

# File Upload

Upload files to MPC Files directly to storage using a multipart upload. Your client asks the Files API to start an upload, gets a pre-signed URL for each part, sends the bytes straight to storage, and then tells the Files API to finish. File bytes never pass through the Files API, so large files upload quickly and reliably.

The same flow is used by MPC users, backend-to-backend integrations and member-facing apps.

## Overview

| Step | Call | Purpose |
|---|---|---|
| 1 | `POST /v1/files/upload/start` | Register the file and receive a `file_handle` |
| 2 | `POST /v1/files/upload/part/{part_number}` | Get a pre-signed URL for one part (repeat per part) |
| 3 | `PUT {presigned_url}` | Upload the part's bytes directly to storage and keep the returned `ETag` |
| 4 | `POST /v1/files/upload/finish` | Assemble the parts into the final file (optionally activate it) |
| 5 | `GET /v1/files/upload/status` | *(Optional)* Poll processing status and get a preview URL |
| 6 | `POST /v1/files/upload/activate` | Activate the file, if it wasn't activated in step 4 |

```mermaid
sequenceDiagram
    participant C as Client
    participant F as Files API
    participant S as Storage (S3)
    C->>F: POST /v1/files/upload/start
    F-->>C: file_handle
    loop For each part
        C->>F: POST /v1/files/upload/part/{n}
        F-->>C: url + headers
        C->>S: PUT url (part bytes)
        S-->>C: ETag
    end
    C->>F: POST /v1/files/upload/finish (parts + ETags)
    F-->>C: accepted
    opt Poll
        C->>F: GET /v1/files/upload/status
        F-->>C: status, url
    end
    C->>F: POST /v1/files/upload/activate
    F-->>C: active
```

## Before you start

**Authentication.** All Files API calls require the standard MPC authentication. Your credentials must be allowed to upload the given `file_type`; otherwise `start` returns `403 Forbidden`.

**Splitting the file into parts.**

- Every part except the last must be **at least 5 MiB**. The last part can be any size.
- A part can be at most **5 GiB**, and a file can have at most **10,000** parts.
- Files smaller than 5 MiB are uploaded as a single part (`part_number` = 1).
- Part numbers start at **1** and must be consecutive.
- Parts can be uploaded in parallel and in any order.

**Browser clients.** Read the `ETag` response header from each `PUT` to storage — you need it to finish the upload.

## File lifecycle

| Status | Meaning |
|---|---|
| `upload_in_progress` | Upload started; parts are being uploaded |
| `completing` | `finish` was called; parts are being assembled |
| `completed` | File is stored but not yet active |
| `active` | File is active and ready to use |

---

## 1. Start the upload

`POST /v1/files/upload/start`

Registers the file and opens a multipart upload.

### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `file_type` | string | Yes | Type of file in MPC. Determines permissions and validation rules. |
| `filename` | string | Yes | Original file name, e.g. `receipt.jpg`. |
| `mimetype` | string | Yes | MIME type, e.g. `image/jpeg`. |
| `size` | integer | Yes | Total file size in bytes. |
| `file_identifier` | string | No | ID of the object the file belongs to. Can also be set in `finish` or `activate`. |
| `file_subidentifier` | string | No | Additional identifier of the object the file belongs to. |

```json
{
  "file_type": "receipt",
  "filename": "20240927_164634.jpg",
  "mimetype": "image/jpeg",
  "size": 312077,
  "file_identifier": "12345"
}
```

### Response `200 OK`

| Field | Type | Description |
|---|---|---|
| `file_handle` | string | Unique, 32-character identifier of the file. Use it in every following call. |

```json
{
  "file_handle": "q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u"
}
```

### Errors

| Status | When |
|---|---|
| `400` / `422` | Missing or invalid field (e.g. unsupported `mimetype`, size above the limit for this `file_type`) |
| `401` | Missing or invalid credentials |
| `403` | Not permitted to upload this `file_type` |

---

## 2. Get a pre-signed URL for a part

`POST /v1/files/upload/part/{part_number}`

Returns a pre-signed URL and the headers to use when uploading one part to storage. Call it once per part.

### Path parameters

| Parameter | Type | Description |
|---|---|---|
| `part_number` | integer | Part number, from `1` to `10000`. |

### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `file_handle` | string | Yes | Value returned by `start`. |
| `size` | integer | Yes | Size of this part in bytes. |
| `md5` | string | Yes | Base64-encoded MD5 digest of this part's bytes. Storage rejects the part if it doesn't match. |

```json
{
  "file_handle": "q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u",
  "size": 312077,
  "md5": "dqt0LFjuwom3N7+rgvhTIg=="
}
```

### Response `200 OK`

| Field | Type | Description |
|---|---|---|
| `url` | string | Pre-signed URL to `PUT` the part to. The URL expires after a short time; request a new one if it does. |
| `headers` | object | Headers you must send, unchanged, with the `PUT`. |
| `part` | integer | Part number this URL is for. |

```json
{
  "url": "https://<bucket>.s3.eu-central-1.amazonaws.com/<key>?partNumber=1&uploadId=...&X-Amz-Signature=...",
  "headers": {
    "Content-MD5": "dqt0LFjuwom3N7+rgvhTIg==",
    "Content-Type": "image/jpeg"
  },
  "part": 1
}
```

### Errors

| Status | When |
|---|---|
| `404` | Unknown `file_handle` |
| `422` | Invalid `part_number`, `size` or `md5`, or the upload is no longer in progress |

---

## 3. Upload the part to storage

`PUT {url}`

Send the raw bytes of the part to the `url` from step 2, with **all** `headers` from step 2. Do not add an `Authorization` header — authorization is in the URL.

```bash
curl -X PUT "$PART_URL" \
  -H "Content-MD5: dqt0LFjuwom3N7+rgvhTIg==" \
  -H "Content-Type: image/jpeg" \
  --data-binary @part-1.bin \
  -D -
```

A successful upload returns `200 OK` with an `ETag` response header, for example:

```
ETag: "76ab742c58eec289b737bfab82f85322"
```

Store the `ETag` (including the quotes) together with the part number. If the upload fails, retry the same part — get a new URL if the old one has expired.

---

## 4. Finish the upload

`POST /v1/files/upload/finish`

Tells the Files API that all parts are uploaded. The parts are assembled asynchronously; the file moves to `completing` and then to `completed` (or `active`, if `activate` is `true`).

### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `file_handle` | string | Yes | Value returned by `start`. |
| `parts` | array | Yes | Every uploaded part, sorted by `part_number`. |
| `parts[].part_number` | integer | Yes | Part number. |
| `parts[].etag` | string | Yes | `ETag` returned by storage for this part. |
| `activate` | boolean | No | Activate the file as soon as it's completed. Default `false`. Requires `file_identifier` to be set. |
| `file_identifier` | string | No | Sets or overrides the value given in `start`. |
| `file_subidentifier` | string | No | Sets or overrides the value given in `start`. |

```json
{
  "file_handle": "q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u",
  "activate": true,
  "file_identifier": "12345",
  "parts": [
    { "part_number": 1, "etag": "\"76ab742c58eec289b737bfab82f85322\"" }
  ]
}
```

### Response `202 Accepted`

```json
{
  "file_handle": "q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u",
  "status": "completing"
}
```

### Errors

| Status | When |
|---|---|
| `404` | Unknown `file_handle` |
| `422` | Missing or invalid `parts`, or the upload was already finished |

---

## 5. Check upload status (optional)

`GET /v1/files/upload/status?file_handle={file_handle}`

Use it to wait until the file is ready after `finish`. Poll with a back-off (e.g. every 1–2 seconds).

### Query parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `file_handle` | string | Yes | Value returned by `start`. |

### Response `200 OK`

| Field | Type | Description |
|---|---|---|
| `status` | string | One of `upload_in_progress`, `completing`, `completed`, `active`. See [File lifecycle](#file-lifecycle). |
| `url` | string \| null | URL to fetch the file, e.g. for a preview. Available once the file is `completed`. |

```json
{
  "status": "completed",
  "url": "https://<files-cdn>/q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u"
}
```

---

## 6. Activate the file

`POST /v1/files/upload/activate`

Activates a completed file. Not needed if you sent `"activate": true` in `finish`.

### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `file_handle` | string | Yes | Value returned by `start`. |
| `file_identifier` | string | No* | Sets or overrides the stored value. *Required if it wasn't set in `start` or `finish`. |
| `file_subidentifier` | string | No | Sets or overrides the stored value. |

```json
{
  "file_handle": "q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u",
  "file_identifier": "12345"
}
```

### Response `200 OK`

```json
{
  "file_handle": "q8ZkT3mVn0aX7pLr2cYbH5wEjF9sGd1u",
  "status": "active"
}
```

### Errors

| Status | When |
|---|---|
| `404` | Unknown `file_handle` |
| `422` | `file_identifier` is not set on the file |
| `422` | Upload is not completed yet — check [status](#5-check-upload-status-optional) and retry |

---

## Full example (JavaScript)

```js
const API = "https://<files-api-host>";
const PART_SIZE = 8 * 1024 * 1024; // 8 MiB (minimum 5 MiB, except the last part)

async function md5Base64(blob) {
  // Use a library such as spark-md5; Web Crypto doesn't support MD5.
  const hex = SparkMD5.ArrayBuffer.hash(await blob.arrayBuffer());
  return btoa(hex.match(/../g).map(h => String.fromCharCode(parseInt(h, 16))).join(""));
}

async function api(path, body, method = "POST") {
  const res = await fetch(`${API}${path}`, {
    method,
    headers: { "Content-Type": "application/json", ...authHeaders() },
    body: body && JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`${path}: ${res.status}`);
  return res.json();
}

async function uploadFile(file, fileType, fileIdentifier) {
  // 1. Start
  const { file_handle } = await api("/v1/files/upload/start", {
    file_type: fileType,
    filename: file.name,
    mimetype: file.type,
    size: file.size,
    file_identifier: fileIdentifier,
  });

  // 2–3. Upload parts
  const parts = [];
  for (let n = 1, offset = 0; offset < file.size; n++, offset += PART_SIZE) {
    const chunk = file.slice(offset, offset + PART_SIZE);
    const { url, headers } = await api(`/v1/files/upload/part/${n}`, {
      file_handle,
      size: chunk.size,
      md5: await md5Base64(chunk),
    });
    const put = await fetch(url, { method: "PUT", headers, body: chunk });
    if (!put.ok) throw new Error(`Part ${n} failed: ${put.status}`);
    parts.push({ part_number: n, etag: put.headers.get("ETag") });
  }

  // 4. Finish and activate
  await api("/v1/files/upload/finish", { file_handle, parts, activate: true });

  // 5. Wait until active
  for (;;) {
    const { status, url } = await api(
      `/v1/files/upload/status?file_handle=${file_handle}`, null, "GET");
    if (status === "active") return { file_handle, url };
    await new Promise(r => setTimeout(r, 1500));
  }
}
```

## Troubleshooting

| Problem | Cause and fix |
|---|---|
| Storage returns `403 SignatureDoesNotMatch` | Headers sent with the `PUT` differ from the ones returned in step 2. Send them exactly as returned. |
| Storage returns `400 BadDigest` | `md5` doesn't match the bytes sent. Compute it over exactly the bytes of that part. |
| Storage returns `403 Request has expired` | The pre-signed URL expired. Request a new one for the same part. |
| `ETag` is `null` in the browser | The response header isn't readable by your script. Contact MPC support. |
| `finish` returns `422` | A part is missing, too small (under 5 MiB and not the last), or an `ETag` is wrong. |
| `activate` returns `422` | Set `file_identifier`, or wait for status `completed`. |
