Files
The Files API moves files between your machine and a session, whose browser runs on another machine and cannot open your files.
- Session files are in one session's
/filesfolder. You upload a file there so that a page can use it, and the files that the browser downloads are saved there. Steel keeps them after the session ends, so that you can download them. - Global files belong to your organization and do not depend on a session. Upload a file once, and copy it into any session.
Before you begin
Put your Steel API key in the STEEL_API_KEY environment variable. Then install the Steel SDK and Playwright.
npm install steel-sdk playwrightpython3 -m venv .venv
source .venv/bin/activate
pip install steel-sdk playwrightgo mod init upload
go get github.com/steel-dev/sdk/gocargo new upload
cd upload
cargo add steel-rs
cargo add tokio --features macros,rt-multi-threadIn Go and Rust, install only the SDK, as the Go and Rust SDK pages show. The code that drives the browser uses Playwright, so it is in TypeScript and Python only.
Upload a file to a session
Call client.sessions.files.upload with a running session's ID and the file. The response has the file's path in the session, its size in bytes and its lastModified time.
This program creates a session, uploads data.csv from the current folder, prints where the file is in the session, and releases the session.
import { createReadStream } from "node:fs";
import Steel from "steel-sdk";
const client = new Steel();
const session = await client.sessions.create();
try {
const uploaded = await client.sessions.files.upload(session.id, {
file: createReadStream("data.csv"),
path: "data.csv",
});
console.log(uploaded.path, uploaded.size);
} finally {
await client.sessions.release(session.id);
}from pathlib import Path
from steel import Steel
client = Steel()
session = client.sessions.create()
try:
uploaded = client.sessions.files.upload(
session.id,
file=Path("data.csv"),
path="data.csv",
)
print(uploaded.path, int(uploaded.size))
finally:
client.sessions.release(session.id)package main
import (
"context"
"fmt"
"io"
"log"
"os"
"github.com/steel-dev/sdk/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
client := steel.NewClient()
session, err := client.Sessions.New(ctx, steel.SessionNewParams{})
if err != nil {
return err
}
defer func() {
if _, err := client.Sessions.Release(ctx, session.ID); err != nil {
log.Print(err)
}
}()
file, err := os.Open("data.csv")
if err != nil {
return err
}
defer file.Close()
uploaded, err := client.Sessions.Files.Upload(ctx, session.ID, steel.SessionFileUploadParams{
File: steel.F[io.Reader](file),
Path: steel.F("data.csv"),
})
if err != nil {
return err
}
fmt.Println(uploaded.Path, uploaded.Size)
return nil
}#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = steel_rs::Client::new();
let session = client
.sessions()
.create(steel_rs::SessionCreateParams::default())
.await?;
let result: Result<(), Box<dyn std::error::Error>> = async {
let uploaded = client
.sessions()
.files()
.upload(
&session.id,
steel_rs::SessionFileUploadParams {
path: Some("data.csv".to_owned()),
..steel_rs::SessionFileUploadParams::new(
steel_rs::Upload::open("data.csv").await?,
)
},
)
.await?;
println!("{} {}", uploaded.path, uploaded.size);
Ok(())
}
.await;
client.sessions().release(&session.id).await?;
result
}Run the program:
npx tsx upload.mtspython upload.pygo run .cargo runThe program prints the file's path in the session and its size.
/files/data.csv 2048The program passes path to name the file. Steel does not use the name of the file that you upload. Without path, it gives the file a random ID as its name. To put the file in a folder, pass a path such as "reports/data.csv". To let Steel fetch the file, pass a public http:// or https:// URL in file instead of the content. The SDKs take only file content in file, so send that request without the SDK, as the example in Keep global files does.
You can upload only while the session runs.
Use the file on a page
Uploading puts the file in the session. A page still needs the file in its file input. Pass the path from the upload to the input with the CDP (Chrome DevTools Protocol) command DOM.setFileInputFiles. Put the import at the top of the program above, and the rest in its try block, after the upload. The code connects Playwright to the session and fills the file input with the ID load-file:
import { chromium } from "playwright";
const browser = await chromium.connectOverCDP(session.websocketUrl);
const context = browser.contexts()[0];
const page = context.pages()[0] ?? (await context.newPage());
await page.goto("https://www.csvplot.com/");
const cdp = await context.newCDPSession(page);
const document = await cdp.send("DOM.getDocument");
const input = await cdp.send("DOM.querySelector", {
nodeId: document.root.nodeId,
selector: "#load-file",
});
await cdp.send("DOM.setFileInputFiles", {
files: [uploaded.path],
nodeId: input.nodeId,
});from playwright.sync_api import sync_playwright
playwright = sync_playwright().start()
browser = playwright.chromium.connect_over_cdp(session.websocket_url)
context = browser.contexts[0]
page = context.pages[0] if context.pages else context.new_page()
page.goto("https://www.csvplot.com/")
cdp = context.new_cdp_session(page)
document = cdp.send("DOM.getDocument")
input_node = cdp.send(
"DOM.querySelector",
{"nodeId": document["root"]["nodeId"], "selector": "#load-file"},
)
cdp.send(
"DOM.setFileInputFiles",
{"files": [uploaded.path], "nodeId": input_node["nodeId"]},
)The page then reads the file as if a person had picked it. With Commands, the upload command does the same in one step. Pass it the session file's name.
Download files from a session
Files that the browser downloads are saved in /files, next to the files that you uploaded. client.sessions.files.list returns all of them. It works during the session and after you release it. List session files says in what order.
const files = await client.sessions.files.list(session.id);
for (const file of files.data) {
console.log(file.path, file.size);
}files = client.sessions.files.list(session.id)
for file in files.data:
print(file.path, int(file.size))files, err := client.Sessions.Files.List(ctx, session.ID)
if err != nil {
return err
}
for _, file := range files.Data {
fmt.Println(file.Path, file.Size)
}let files = client.sessions().files().list(&session.id).await?;
for file in files.data {
println!("{} {}", file.path, file.size);
}/files/report.pdf 589
/files/data.csv 3207Playwright changes these names. When it connects over CDP, it tells the browser to save each download under a random ID, such as /files/ef4853ce-7350-4119-888e-861987165947, instead of the file's own name. To keep the names, reset the download behavior right after you connect:
const cdp = await browser.newBrowserCDPSession();
await cdp.send("Browser.setDownloadBehavior", { behavior: "default" });cdp = browser.new_browser_cdp_session()
cdp.send("Browser.setDownloadBehavior", {"behavior": "default"})To download one file, pass its path without the /files/ prefix, such as report.pdf. A path that starts with / fails.
import { writeFile } from "node:fs/promises";
const response = await client.sessions.files.download(session.id, "report.pdf");
await writeFile("report.pdf", Buffer.from(await response.arrayBuffer()));response = client.sessions.files.download("report.pdf", session_id=session.id)
response.write_to_file("report.pdf")response, err := client.Sessions.Files.Download(ctx, session.ID, "report.pdf")
if err != nil {
return err
}
defer response.Body.Close()
pdf, err := io.ReadAll(response.Body)
if err != nil {
return err
}
if err := os.WriteFile("report.pdf", pdf, 0o644); err != nil {
return err
}let response = client
.sessions()
.files()
.download(&session.id, "report.pdf")
.await?;
std::fs::write("report.pdf", response)?;To download all of the session's files as one zip file, call downloadArchive:
const archive = await client.sessions.files.downloadArchive(session.id);
await writeFile("session-files.zip", Buffer.from(await archive.arrayBuffer()));archive = client.sessions.files.download_archive(session.id)
archive.write_to_file("session-files.zip")archive, err := client.Sessions.Files.DownloadArchive(ctx, session.ID)
if err != nil {
return err
}
defer archive.Body.Close()
zip, err := io.ReadAll(archive.Body)
if err != nil {
return err
}
if err := os.WriteFile("session-files.zip", zip, 0o644); err != nil {
return err
}let archive = client
.sessions()
.files()
.download_archive(&session.id)
.await?;
std::fs::write("session-files.zip", archive)?;Check the size or content of what you download. A click on a download button does not prove that the file arrived.
Keep global files
Upload a global file with client.files.upload. Pass path to name the file. Without it, Steel names the file with a random ID and the .bin extension. The response has the file's path.
import { createReadStream } from "node:fs";
const globalFile = await client.files.upload({
file: createReadStream("data.csv"),
path: "data.csv",
});
console.log(globalFile.path);from pathlib import Path
global_file = client.files.upload(
file=Path("data.csv"),
path="data.csv",
)
print(global_file.path)import (
"io"
"os"
)
file, err := os.Open("data.csv")
if err != nil {
return err
}
defer file.Close()
globalFile, err := client.Files.Upload(ctx, steel.FileUploadParams{
File: steel.F[io.Reader](file),
Path: steel.F("data.csv"),
})
if err != nil {
return err
}
fmt.Println(globalFile.Path)let global_file = client
.files()
.upload(steel_rs::FileUploadParams {
path: Some("data.csv".to_owned()),
..steel_rs::FileUploadParams::new(steel_rs::Upload::open("data.csv").await?)
})
.await?;
println!("{}", global_file.path);data.csvTo copy a global file into a session, upload to the session and pass the global file's path in file, instead of its content. The SDKs take only file content in file, and their types refuse a string there, so this code sends the request without the SDK. Without path, the session file gets the global file's name. In Python, the code uses httpx, which comes with steel-sdk.
const form = new FormData();
form.append("file", "data.csv");
const response = await fetch(
`https://api.steel.dev/v1/sessions/${session.id}/files`,
{
method: "POST",
headers: { "steel-api-key": process.env.STEEL_API_KEY! },
body: form,
},
);
const uploaded = await response.json();
console.log(uploaded.path);import os
import httpx
response = httpx.post(
f"https://api.steel.dev/v1/sessions/{session.id}/files",
headers={"steel-api-key": os.environ["STEEL_API_KEY"]},
files={"file": (None, "data.csv")},
)
print(response.json()["path"])/files/data.csvclient.files.list lists the global files, and client.files.download downloads one by its path, in the same way as for session files.
Delete files
Delete a session file by its path, without the /files/ prefix, or delete all of the session's files. You can delete session files only while the session runs.
await client.sessions.files.delete(session.id, "report.pdf");
await client.sessions.files.deleteAll(session.id);client.sessions.files.delete("report.pdf", session_id=session.id)
client.sessions.files.delete_all(session.id)if err := client.Sessions.Files.Delete(ctx, session.ID, "report.pdf"); err != nil {
return err
}
if err := client.Sessions.Files.DeleteAll(ctx, session.ID); err != nil {
return err
}client
.sessions()
.files()
.delete(&session.id, "report.pdf")
.await?;
client.sessions().files().delete_all(&session.id).await?;Delete a global file by its path:
await client.files.delete("data.csv");client.files.delete("data.csv")if err := client.Files.Delete(ctx, "data.csv"); err != nil {
return err
}client.files().delete("data.csv").await?;Check that it worked
List the session's files with client.sessions.files.list. The uploaded file is there, with the path /files/data.csv and the size that the upload printed. For a file that you download, compare the size of the file on your machine with its size in the list. When the two match, the whole file arrived.
Troubleshooting
A file path is required
{
"error": "Bad Request",
"message": "A file path is required. Provide a relative path with no leading '/' or '..' segments, e.g. 'downloads/report.pdf'.",
"retryable": false,
"linkToDocs": "https://docs.steel.dev/overview/files-api/overview"
}Cause: The path starts with /, holds a .. segment, or is empty. This happens when you pass the path from an upload or a list, such as /files/report.pdf, to a download or a delete.
Fix: Remove the /files/ prefix, and pass report.pdf.
Verify: The download returns the file.
The session is not running
Cause: You uploaded or deleted a file after the session ended. The response has the status 409, and its message starts with Session 'SESSION_ID' is and the session's status.
Fix: Upload and delete files before you release the session. To list and download a released session's files, use the calls in Download files from a session.
Verify: The upload returns the file's path.
Next steps
- Files API: List and download global files, and see what each call takes and returns.