# 上传数据
<subtitle>将本地文件上传到沙箱。</subtitle>

您可以使用 `files.write()` 方法将数据上传到沙箱。

## 上传单个文件

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# 从本地文件系统读取文件
with open("path/to/local/file", "rb") as file:
  # 上传文件到沙箱
  sandbox.files.write("/path/in/sandbox", file)
```

## 使用预签名 URL 上传

有时，您可能希望让来自未授权环境（如浏览器）的用户将文件上传到沙箱。对于这种用例，您可以使用预签名 URL 让用户安全地上传文件。

您只需使用 `secure=True` 选项创建沙箱。然后将生成一个带有签名的上传 URL，该签名仅允许授权用户上传文件。您可以选择性地为 URL 设置过期时间，使其仅在有限时间内有效。

```python
from ucloud_sandbox import Sandbox
import requests

# 启动安全沙箱（默认情况下所有操作都必须授权）
sandbox = Sandbox.create(timeout=12_000, secure=True)

# 创建一个有效期为 10 秒的预签名文件上传 URL
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)

# 文件现在在沙箱中可用，您可以读取它
content = sandbox.files.read('/path/in/sandbox')
```

## 上传目录/多个文件

```python
import os
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

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/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)
```
