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

# 文件上传

export const SandboxConfigHint = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Note>在运行本文档中的示例代码前，请确保您已正确配置环境变量，详情请参考 <a href="/sandbox/get-start#配置环境变量">配置环境变量</a>。</Note>;
  }
};

我们可以将本地文件上传到沙箱内。

<SandboxConfigHint />

## 上传单个文件

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={null}
  import fs from 'fs'
  import { Sandbox } from 'ppio-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // 从本地文件系统读取文件内容
  const localFilePath = '../local-test-file'
  const content = fs.readFileSync(localFilePath, 'utf8')

  // 将文件上传到沙箱
  const filePathInSandbox = '/tmp/test-file'
  const result = await sandbox.files.write(filePathInSandbox, content)
  console.log(result)

  await sandbox.kill()
  ```

  ```python Python icon="python" theme={null}
  from ppio_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create()

  # 从本地文件系统读取文件内容
  local_file_path = '../local-test-file'
  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()
  ```
</CodeGroup>

## 上传目录/多个文件

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={null}
  import fs from 'fs'
  import path from 'path'
  import { Sandbox } from 'ppio-sandbox/code-interpreter'

  const sandbox = await Sandbox.create()

  // 读取目录中的所有文件，并将它们的路径和内容存储在一个数组中
  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 localDirectoryPath = '../local-test-dir'
  const files = readDirectoryFiles(localDirectoryPath);
  console.log(files); 
  // 输出示例：
  // [
  //   {
  //     path: '../local-test-dir/local-test-file-1',
  //     data: 'test-file-content'
  //   },
  //   {
  //     path: '../local-test-dir/local-test-file-2',
  //     data: 'test-file-content'
  //   }
  // ]

  // 指定上传到沙箱里的文件路径
  files.forEach(file => {
    file.path = file.path.replace('../local-test-dir', '/tmp')
  })

  const result = await sandbox.files.write(files)
  console.log(result)
  // 输出示例：
  // [
  //   {
  //     name: 'local-test-file-1',
  //     path: '/tmp/local-test-file-1',
  //     type: 'file'
  //   },
  //   {
  //     name: 'local-test-file-2',
  //     path: '/tmp/local-test-file-2',
  //     type: 'file'
  //   }
  // ]

  await sandbox.kill()
  ```

  ```python Python icon="python" theme={null}
  import os
  from ppio_sandbox.code_interpreter 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

  local_directory_path = '../local-test-dir'
  files = read_directory_files(local_directory_path)
  print(files)
  # 输出示例：
  # [{'path': '../local-test-dir/local-test-file-1', 'data': b'test-file-content'}, {'path': '../local-test-dir/local-test-file-2', 'data': b'test-file-content'}]

  # 指定上传到沙箱里的文件路径
  for file in files:
      file['path'] = file['path'].replace('../local-test-dir', '/tmp')

  result = sandbox.files.write_files(files)
  print(result)
  # 输出示例：
  # [WriteInfo(name='local-test-file-1', type='file', path='/tmp/local-test-file-1'), WriteInfo(name='local-test-file-2', type='file', path='/tmp/local-test-file-2')]

  sandbox.kill()
  ```
</CodeGroup>
