# Upload Data
<subtitle>Upload local files or data streams to the sandbox file system.</subtitle>

You can use the `files.write()` method to upload data to the sandbox.

## Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

## Upload Single File

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Read file from local file system
with open("path/to/local/file", "rb") as file:
    # Upload file to sandbox
    sandbox.files.write("/path/in/sandbox", file)
```

## Upload Using Presigned URL

Sometimes, you may want to allow users in unauthorized environments (such as browsers) to upload files to the sandbox. For this use case, you can use presigned URLs to allow users to securely upload files.

All you need to do is create a sandbox with the `secure=True` option. An upload URL will then be generated with a signature that only allows authorized users to upload files. You can optionally set an expiration time for the URL, making it valid only for a limited time.

```python
import requests
from ucloud_sandbox import Sandbox

# Start secure sandbox (by default, all operations must be authorized)
sandbox = Sandbox.create(timeout=12_000, secure=True)

# Create a presigned upload URL with a 10-second expiration time
signed_url = sandbox.upload_url(path="demo.txt", user="user", use_signature_expiration=10_000)

form_data = {"file": "file content"}
requests.post(signed_url, data=form_data)
```

## Upload Directory/Multiple Files

```python
import os
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

def read_directory_files(directory_path):
    files = []
    
    # Iterate through all files in the directory
    for filename in os.listdir(directory_path):
        file_path = os.path.join(directory_path, filename)
        
        # Skip if it's a directory
        if os.path.isfile(file_path):
            # Read file content in binary mode
            with open(file_path, "rb") as file:
                files.append({
                    'path': file_path,
                    'data': file.read()
                })
    
    return files

files = read_directory_files("/local/dir")
print(files)
# [
#   {"path": "/local/dir/file1.txt", "data": "File 1 contents..."},
#   {"path": "/local/dir/file2.txt", "data": "File 2 contents..."},
#   ...
# ]

sandbox.files.write_files(files)
```
