> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ppio.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Upload files to a sandbox

> Upload a single local file, a directory or several files to a sandbox with files.write(), or let a browser upload through a pre-signed URL.

`files.write()` sends data from local code into the sandbox filesystem. A second path covers uploads from a browser, which holds no API key. The backend issues a pre-signed upload URL, and the browser posts the file to it.

> [!NOTE]
>
> Install the SDK, or the CLI for `ppio` commands, and set the `PPIO_API_KEY` and `PPIO_DOMAIN` environment variables before running these examples. See [Quickstart](https://docs.ppio.ai/sandbox/quickstart.md) and [Install and authenticate](https://docs.ppio.ai/sandbox/cli/install.md).

## Upload a single file

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.code_interpreter.create()

# Write a local file to upload
local_file_path = 'local-test-file'
with open(local_file_path, 'w') as file:
    file.write('test-file-content')

with open(local_file_path, 'rb') as file:
    file_path_in_sandbox = '/tmp/test-file'
    result = sandbox.files.write(file_path_in_sandbox, file)
    print(result)

sandbox.kill()
```

```javascript Node.js theme={null}
// index.mts
import fs from 'fs'
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.codeInterpreter.create()

// Write a local file to upload
const localFilePath = 'local-test-file'
fs.writeFileSync(localFilePath, 'test-file-content')

// Read the file from the local filesystem
const content = fs.readFileSync(localFilePath, 'utf8')

// Upload the file to the sandbox
const filePathInSandbox = '/tmp/test-file'
const result = await sandbox.files.write(filePathInSandbox, content)
console.log(result)

await sandbox.kill()
```

## Upload with a pre-signed URL

Pre-signed upload URLs let users upload files securely from environments that hold no API key, such as web browsers. Create the sandbox with the `secure: true` option, then use the SDK on the trusted backend to generate the upload URL.

```mermaid theme={null}
sequenceDiagram
  participant B as Backend SDK
  participant S as Sandbox
  participant U as Browser
  B->>S: create sandbox (secure: true)
  B->>B: generate upload URL
  B-->>U: URL (authorized users only)
  U->>S: POST file to the URL
```

> [!WARNING]
>
> Return the URL only to users authorized by the application, and set a short expiration time. Anyone who holds the URL can use it until it expires.

```python Python theme={null}
from pathlib import Path

import requests
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.code_interpreter.create(secure=True)

# Write a local file to upload
local_file_path = Path('local-test-file')
local_file_path.write_text('test-file-content')
file_path_in_sandbox = '/tmp/test-file'

# Generate pre signature upload URL
signed_url = sandbox.upload_url(
    path=file_path_in_sandbox,
    use_signature_expiration=120,  # optional, in seconds
)

# Simulate browser behavior
with open(local_file_path, 'rb') as f:
    response = requests.post(
        signed_url,
        files={'file': (local_file_path.name, f)},
        timeout=60,
    )
response.raise_for_status()

# SDK Read Back Verification
result = sandbox.files.read(file_path_in_sandbox)
print(result)

sandbox.kill()
```

```javascript Node.js theme={null}
// index.mts
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.codeInterpreter.create({ secure: true })

const filePathInSandbox = '/tmp/test-file'

// Generate pre signature upload URL
const publicUploadUrl = await sandbox.uploadUrl(filePathInSandbox, {
  useSignatureExpiration: 120, // optional, in seconds
})

// Simulate browser behavior
const form = new FormData()
form.append('file', new Blob(['file content']), 'test-file')

const uploadRes = await fetch(publicUploadUrl, {
  method: 'POST',
  body: form,
})
if (!uploadRes.ok) {
  throw new Error(`Upload failed: ${uploadRes.status} ${await uploadRes.text()}`)
}

// SDK Read Back Verification
const result = await sandbox.files.read(filePathInSandbox)
console.log(result)

await sandbox.kill()
```

## Upload a directory or several files

Read a local directory into a list of files, then write the list in one call.

```python Python theme={null}
import os
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.code_interpreter.create()

# Create a local directory to upload
local_directory_path = 'local-test-dir'
os.makedirs(local_directory_path, exist_ok=True)
for name in ('file-1.txt', 'file-2.txt'):
    with open(os.path.join(local_directory_path, name), 'w') as file:
        file.write(name)

def read_directory_files(directory_path):
    files = []

    for filename in os.listdir(directory_path):
        file_path = os.path.join(directory_path, filename)

        if os.path.isfile(file_path):
            with open(file_path, 'rb') as file:
                files.append({
                    'path': file_path,
                    'data': file.read(),
                })
    return files

files = read_directory_files(local_directory_path)
print(files)

for file in files:
    file['path'] = file['path'].replace('local-test-dir', '/tmp')

result = sandbox.files.write_files(files)
print(result)

sandbox.kill()
```

```javascript Node.js theme={null}
// index.mts
import fs from 'fs'
import path from 'path'
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.codeInterpreter.create()

// Create a local directory to upload
const localDirectoryPath = 'local-test-dir'
fs.mkdirSync(localDirectoryPath, { recursive: true })
fs.writeFileSync(path.join(localDirectoryPath, 'file-1.txt'), 'file content 1')
fs.writeFileSync(path.join(localDirectoryPath, 'file-2.txt'), 'file content 2')

const readDirectoryFiles = (directoryPath) => {
  const files = fs.readdirSync(directoryPath)

  const filesArray = files
    .filter((file) => {
      const fullPath = path.join(directoryPath, file)
      return fs.statSync(fullPath).isFile()
    })
    .map((file) => {
      const filePath = path.join(directoryPath, file)

      return {
        path: filePath,
        data: fs.readFileSync(filePath, 'utf8'),
      }
    })

  return filesArray
}

const files = readDirectoryFiles(localDirectoryPath)
console.log(files)

files.forEach((file) => {
  file.path = file.path.replace('local-test-dir', '/tmp')
})

const result = await sandbox.files.write(files)
console.log(result)

await sandbox.kill()
```


## Related topics

- [Work with files in a sandbox](https://docs.ppio.ai/sandbox/filesystem/overview.md)
- [Download files from a sandbox](https://docs.ppio.ai/sandbox/filesystem/download.md)
- [Secure access to sandbox services](https://docs.ppio.ai/sandbox/secured-access.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.