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

# Upload data to sandbox

> Upload files to an E2B sandbox with files.write(): write a single file, stream a large upload, upload multiple files, or share a pre-signed upload URL.

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

## Upload single file

```js JavaScript & TypeScript theme={"theme":"css-variables"}
import fs from 'fs'
import { Sandbox } from 'e2b'

const sandbox = await Sandbox.create()

// Read file from local filesystem
const content = fs.readFileSync('/local/path')
// Upload file to sandbox
await sandbox.files.write('/path/in/sandbox', content)
```

```python Python theme={"theme":"css-variables"}
from e2b import Sandbox

sandbox = Sandbox.create()

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

## Stream an upload

Instead of reading a whole file into memory first, pass a stream (or an iterable of byte chunks) to `files.write()`. Chunks are uploaded as they arrive, so the size of the data doesn't matter.

```js JavaScript & TypeScript theme={"theme":"css-variables"}
import fs from 'fs'
import { Sandbox } from 'e2b'

const sandbox = await Sandbox.create()

// Any AsyncIterable<Uint8Array>, like a Node.js Readable...
await sandbox.files.write('/path/in/sandbox', fs.createReadStream('/local/path'))

// ...or a ReadableStream, like a fetch response body
const response = await fetch('https://example.com/large-file.zip')
await sandbox.files.write('/path/in/sandbox/large-file.zip', response.body)
```

```python Python theme={"theme":"css-variables"}
import requests
from e2b import Sandbox

sandbox = Sandbox.create()

# Any iterable of bytes chunks, like a streamed HTTP response...
with requests.get("https://example.com/large-file.zip", stream=True) as response:
    sandbox.files.write("/path/in/sandbox/large-file.zip", response.iter_content(chunk_size=1024 * 1024))

# ...or a generator
def chunks():
    for part in range(3):
        yield f"part {part}\n".encode()

sandbox.files.write("/path/in/sandbox/parts.txt", chunks())
```

```python Python (async) theme={"theme":"css-variables"}
import httpx
from e2b import AsyncSandbox

sandbox = await AsyncSandbox.create()

# Any async iterable of bytes chunks, like a streamed HTTP response...
async with httpx.AsyncClient() as client:
    async with client.stream("GET", "https://example.com/large-file.zip") as response:
        await sandbox.files.write("/path/in/sandbox/large-file.zip", response.aiter_bytes())

# ...or an async generator
async def chunks():
    for part in range(3):
        yield f"part {part}\n".encode()

await sandbox.files.write("/path/in/sandbox/parts.txt", chunks())
```

Streams are always uploaded as `application/octet-stream` and are never buffered, so `useOctetStream: false` (`use_octet_stream=False` in Python) raises an error for them. `gzip: true` compresses the stream on the fly.

> [!NOTE]
>
> `Sandbox` accepts sync iterables and `AsyncSandbox` accepts async iterables. In browsers that can't stream request bodies (Firefox, Safari), convert the stream to a `Blob` first, for example `await new Response(stream).blob()`.

## Upload with pre-signed URL

Sometimes, you may want to let users from unauthorized environments, like a browser, upload files to the sandbox.
For this use case, you can use pre-signed URLs to let users upload files securely.

Every sandbox has [secured access](https://docs.e2b.dev/sandbox/secured-access.md) enabled, so all you need to do is generate a URL with a signature that allows only authorized users to upload files.
You can optionally set an expiration time for the URL so that it will be valid only for a limited time.

```js JavaScript & TypeScript theme={"theme":"css-variables"}
import { Sandbox } from 'e2b'

// Start a sandbox (all operations must be authorized by default)
const sandbox = await Sandbox.create(template)

// Create a pre-signed URL for file upload with a 10 second expiration
const publicUploadUrl = await sandbox.uploadUrl(
  'demo.txt', {
    useSignatureExpiration: 10_000, // optional
  },
)

// Upload a file with a pre-signed URL (this can be used in any environment, such as a browser)
const form = new FormData()
form.append('file', 'file content')

await fetch(publicUploadUrl, { method: 'POST', body: form })

// File is now available in the sandbox and you can read it
const content = sandbox.files.read('/path/in/sandbox')
```

```python Python theme={"theme":"css-variables"}
from e2b import Sandbox
import requests

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

# Create a pre-signed URL for file upload with a 10 second expiration
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)

# File is now available in the sandbox and you can read it
content = sandbox.files.read('/path/in/sandbox')
```

## Upload directory / multiple files

```js JavaScript & TypeScript theme={"theme":"css-variables"}
import { Sandbox } from 'e2b'

const sandbox = await Sandbox.create()

// Read all files in the directory and store their paths and contents in an array
const readDirectoryFiles = (directoryPath) => {
  // Read all files in the local directory
  const files = fs.readdirSync(directoryPath);

  // Map files to objects with path and data
  const filesArray = files
    .filter(file => {
      const fullPath = path.join(directoryPath, file);
      // Skip if it's a directory
      return fs.statSync(fullPath).isFile();
    })
    .map(file => {
      const filePath = path.join(directoryPath, file);
    
      // Read the content of each file
      return {
        path: filePath,
        data: fs.readFileSync(filePath, 'utf8')
      };
    });

  return filesArray;
};

// Usage example
const files = readDirectoryFiles('/local/dir');
console.log(files); 
// [
//   { path: '/local/dir/file1.txt', data: 'File 1 contents...' },
//   { path: '/local/dir/file2.txt', data: 'File 2 contents...' },
//   ...
// ]

await sandbox.files.write(files)
```

```python Python theme={"theme":"css-variables"}
import os
from e2b 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 contents 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)
```
