Upload data to sandbox

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

Upload single file

import fs from 'fs'
import { Sandbox } from '@e2b/code-interpreter'

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)

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.

import fs from 'fs'
import { Sandbox } from '@e2b/code-interpreter'

// Start a secured sandbox (all operations must be authorized by default)
const sandbox = await Sandbox.create(template, { secure: true })

// Create a pre-signed URL for file upload with a 10 second expiration
const publicUploadUrl = await sandbox.uploadUrl(
  'demo.txt', {
    useSignature: true,
    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 = fs.readFileSync('demo.txt')

Upload directory / multiple files

const fs = require('fs');
const path = require('path');

import { Sandbox } from '@e2b/code-interpreter'

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 = readDirectoryContents('/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)