# 5. Upload Files

<mark style="color:green;">`POST`</mark> `/documentClassification/deleteFiles`

This endpoint enables users to upload files to a specific document classification process.

If a `batchId` is provided in the request, the uploaded files will be added to that existing batch. If `batchId` is omitted, a new batch will be automatically created for the files under the specified `classificationId`.

Files must be uploaded using the `multipart/form-data` content type, which is required for binary file uploads such as PDFs, images, or scanned documents. Ensure the `classificationId` is valid, and that any provided `batchId` already exists within the classification context.

## Server URL

```
https://api.extracta.ai/api/v1
```

## Headers

| Name          | Value                 |
| ------------- | --------------------- |
| Content-Type  | `multipart/form-data` |
| Authorization | `Bearer <token>`      |

## Body

<table><thead><tr><th width="251">Name</th><th width="119">Type</th><th width="115">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>classificationId</code></td><td>string</td><td><code>true</code></td><td>Unique identifier for the extraction.</td></tr><tr><td><code>batchId</code></td><td>string</td><td><code>false</code></td><td>The ID of the batch to add files to.</td></tr><tr><td><code>files</code></td><td>multipart</td><td><code>true</code></td><td><a data-mention href="/pages/GEp82eoMVXcJO7dA0Z4j">/pages/GEp82eoMVXcJO7dA0Z4j</a></td></tr></tbody></table>

For a seamless classification process, please ensure your documents are in one of our supported formats. Check our Supported File Types page for a list of all formats we currently accept and additional details to prepare your files accordingly.

{% content-ref url="/pages/GEp82eoMVXcJO7dA0Z4j" %}
[Broken mention](broken://pages/GEp82eoMVXcJO7dA0Z4j)
{% endcontent-ref %}

## Code Example

**Note for PHP Users:** Currently, the `/uploadFiles` endpoint supports uploading only one file per request. Please ensure you submit individual requests for each file you need to upload.

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');

async function uploadFilesToClassification(token, classificationId, files, batchId = null) {
    const url = "https://api.extracta.ai/api/v1/documentClassification/uploadFiles";
    let formData = new FormData();

    formData.append('classificationId', classificationId);
    if (batchId) {
        formData.append('batchId', batchId);
    }

    files.forEach(file => {
        formData.append('files', fs.createReadStream(file));
    });

    try {
        const response = await axios.post(url, formData, {
            headers: {
                ...formData.getHeaders(),
                'Authorization': `Bearer ${token}`
            }
        });

        return response.data;
    } catch (error) {
        throw error.response ? error.response.data : new Error('An unknown error occurred');
    }
}

async function main() {
    const token = 'apiKey';
    const classificationId = 'classificationId';
    const files = ['test_1.pdf', 'test_2.jpg'];
    const batchId = null; // or specify an existing batchId if needed

    try {
        const response = await uploadFilesToClassification(token, classificationId, files, batchId);
        console.log("Upload Response:", response);
    } catch (error) {
        console.error("Failed to upload files:", error);
    }
}

main();
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import mimetypes

def upload_files_to_classification(token, classification_id, files, batch_id=None):
    url = "https://api.extracta.ai/api/v1/documentClassification/uploadFiles"
    headers = {"Authorization": f"Bearer {token}"}

    # Prepare the files for uploading
    file_streams = [
        (
            "files",
            (
                file,
                open(file, "rb"),
                mimetypes.guess_type(file)[0] or "application/octet-stream",
            ),
        )
        for file in files
    ]
    
    payload = {"classificationId": classification_id}
    if batch_id is not None:
        payload["batchId"] = batch_id

    try:
        response = requests.post(url, files=file_streams, data=payload, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.HTTPError as e:
        if response.status_code >= 400:
            try:
                print("Server returned an error:", response.json())
            except Exception:
                print("Server returned an error:", response.text)
        else:
            print(f"HTTP error occurred: {e}")
    except requests.RequestException as e:
        print(f"Failed to upload files: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    return None

# Example usage
if __name__ == "__main__":
    token = 'apiKey'
    classification_id = 'classificationId'
    files = ['test_1.pdf', 'test_2.jpg']
    batch_id = None  # or specify an existing batch ID if needed

    response = upload_files_to_classification(token, classification_id, files, batch_id)
    if response:
        print("Upload response:", response)
    else:
        print("Upload failed.")
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

function uploadFileToClassification($token, $classificationId, $filePath, $batchId = null) {
    $url = 'https://api.extracta.ai/api/v1/documentClassification/uploadFiles';

    // Initialize cURL session
    $ch = curl_init($url);

    // Prepare the payload
    $payload = [
        'classificationId' => $classificationId,
        'files' => new CURLFile($filePath, mime_content_type($filePath), basename($filePath))
    ];

    if ($batchId !== null) {
        $payload['batchId'] = $batchId;
    }

    // Set cURL options
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: multipart/form-data'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    try {
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            throw new Exception('Curl error: ' . curl_error($ch));
        }

        return $response;
    } catch (Exception $e) {
        return 'Error: ' . $e->getMessage();
    } finally {
        curl_close($ch);
    }
}

// Example usage
$token = 'apiKey';
$classificationId = 'yourClassificationIdHere';
$filePath = './test_1.pdf';
$batchId = null; // or specify an existing batch ID

try {
    $response = uploadFileToClassification($token, $classificationId, $filePath, $batchId);
    echo $response;
} catch (Exception $e) {
    echo "Failed to upload file: " . $e->getMessage();
}

?>
```

{% endtab %}
{% endtabs %}

## Responses

{% tabs %}
{% tab title="200" %}

```json
{
    "status": "uploaded",
    "classificationId": "classificationId",
    "batchId": "batchId",
    "files": [
        {
            "fileId": "fileId",
            "fileName": "file.pdf",
            "numberOfPages": 1,
            "url": "fileUrl"
        }
    ]
}
```

{% endtab %}

{% tab title="400" %}

```json
{
    "status": "error",
    "message": "Classification not found"
}
```

{% endtab %}

{% tab title="500" %}

```json
{
    "status": "error",
    "message": "Internal server error"
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.extracta.ai/document-classification-api/api-endpoints-document-classification/5.-upload-files.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
