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

# File Uploads

> Learn how to upload files to your browser sessions

Hyperbrowser allows you to upload files to your browser sessions. This is useful for a variety of use cases, such as:

* Uploading a CSV file to a website to be used in a form
* Uploading a PDF file to a website to be used in a form
* Uploading a Word document to a website to be used in a form

You can upload files to your remote browser session via the Session Uploads API. The name of the file that is uploaded is what it will be saved as in the remote browser session and be stored in the `/tmp/uploads` directory.

<Note>
  **Self-Hosted Hyperbrowser**: For some instances of self-hosted Hyperbrowser, uploads will be available at `/tmp/<sessionId>/uploads` on the host machine.
</Note>

<Tabs>
  <Tab title="Playwright">
    <CodeGroup>
      ```typescript Node.js theme={null}
      import { Hyperbrowser } from "@hyperbrowser/sdk";
      import { chromium } from "playwright-core";
      import { config } from "dotenv";
      // import fs from "fs";

      config();

      const hbClient = new Hyperbrowser({
        apiKey: process.env.HYPERBROWSER_API_KEY,
      });

      const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

      const main = async () => {
        const session = await hbClient.sessions.create();
        const liveUrl = session.liveUrl;
        console.log("Live URL:", liveUrl);

        const fileName = "FILENAME.EXTENSION";

        try {
          const result = await hbClient.sessions.uploadFile(session.id, {
            fileInput: fileName,
          });

          // or
          // const fileStream = fs.createReadStream(fileName);
          // const result = await hbClient.sessions.uploadFile(session.id, {
          //   fileInput: fileStream,
          // });

          console.log("Upload success:", result);

          const browser = await chromium.connectOverCDP(session.wsEndpoint);
          const context = browser.contexts()[0];
          const page = context.pages()[0];

          await page.goto("https://browser-tests-alpha.vercel.app/api/upload-test");

          const cdp = await context.newCDPSession(page);
          const root = await cdp.send("DOM.getDocument");

          const inputNode = await cdp.send("DOM.querySelector", {
            nodeId: root["root"]["nodeId"],
            selector: "#fileUpload",
          });
          const remoteFilePath = result.filePath;
          if (!remoteFilePath) {
            console.error("Remote file path not found");
            return;
          }

          await cdp.send("DOM.setFileInputFiles", {
            files: [remoteFilePath],
            nodeId: inputNode["nodeId"],
          });

          await sleep(20_000);
        } catch (err) {
          console.error("Error uploading file:", err);
        } finally {
          await hbClient.sessions.stop(session.id);
        }
      };

      main().catch((err) => {
        console.error(err);
        process.exit(1);
      });
      ```

      ```python Python theme={null}
      import asyncio
      from hyperbrowser import AsyncHyperbrowser
      from playwright.async_api import async_playwright
      from dotenv import load_dotenv
      import os

      load_dotenv()

      hb_client = AsyncHyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY"))


      async def main():
          session = await hb_client.sessions.create()
          live_url = session.live_url
          print("Live URL:", live_url)
          file_name = "FILENAME.EXTENSION"

          try:
              result = await hb_client.sessions.upload_file(session.id, file_name)

              # or upload the file itself
              # with open(file_name, "rb") as f:
              #    result = await hb_client.sessions.upload_file(session.id, f)

              print("Upload success:", result)
              async with async_playwright() as p:
                  browser = await p.chromium.connect_over_cdp(session.ws_endpoint)
                  context = browser.contexts[0]
                  page = context.pages[0]

                  # Navigate to a website
                  await page.goto("https://browser-tests-alpha.vercel.app/api/upload-test")

                  cdp = await context.new_cdp_session(page)
                  root = await cdp.send("DOM.getDocument")

                  input_node = await cdp.send(
                      "DOM.querySelector",
                      {"nodeId": root["root"]["nodeId"], "selector": "#fileUpload"},
                  )

                  remote_file_path = result.file_path
                  if not remote_file_path:
                      print("Remote file path not found")
                      return
                  await cdp.send(
                      "DOM.setFileInputFiles",
                      {"files": [remote_file_path], "nodeId": input_node["nodeId"]},
                  )

                  await asyncio.sleep(20)

          except Exception as e:
              print(f"Error: {e}")
          finally:
              await hb_client.sessions.stop(session.id)


      if __name__ == "__main__":
          asyncio.run(main())
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Puppeteer">
    <CodeGroup>
      ```typescript Node.js theme={null}
      import { Hyperbrowser } from "@hyperbrowser/sdk";
      import { connect } from "puppeteer-core";
      import { config } from "dotenv";
      // import fs from "fs";

      config();

      const hbClient = new Hyperbrowser({
        apiKey: process.env.HYPERBROWSER_API_KEY,
      });

      const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

      const main = async () => {
        const session = await hbClient.sessions.create();
        const liveUrl = session.liveUrl;
        console.log("Live URL:", liveUrl);

        const fileName = "FILENAME.EXTENSION";

        try {
          const result = await hbClient.sessions.uploadFile(session.id, {
            fileInput: fileName,
          });

          // or
          // const fileStream = fs.createReadStream(fileName);
          // const result = await hbClient.sessions.uploadFile(session.id, {
          //   fileInput: fileStream,
          // });

          console.log("Upload success:", result);

          const browser = await connect({ browserWSEndpoint: session.wsEndpoint });
          const defaultContext = browser.defaultBrowserContext();
          const page = await defaultContext.newPage();

          await page.goto("https://browser-tests-alpha.vercel.app/api/upload-test");
          const remoteFilePath = result.filePath;
          if (!remoteFilePath) {
            console.error("Remote file path not found");
            return;
          }

          const input = await page.$("#fileUpload");

          if (input) {
            await (input as any).uploadFile(remoteFilePath);
          } else {
            console.error("Input element not found");
            return;
          }

          await sleep(20_000);
        } catch (err) {
          console.error("Error uploading file:", err);
        } finally {
          await hbClient.sessions.stop(session.id);
        }
      };

      main().catch((err) => {
        console.error(err);
        process.exit(1);
      });
      ```

      ```python Python theme={null}
      import asyncio
      from hyperbrowser import AsyncHyperbrowser
      from pyppeteer import connect
      from dotenv import load_dotenv
      import os

      load_dotenv()

      hb_client = AsyncHyperbrowser(api_key=os.getenv("HYPERBROWSER_API_KEY"))


      async def main():
          session = await hb_client.sessions.create()
          live_url = session.live_url
          print("Live URL:", live_url)

          file_name = "FILENAME.EXTENSION"

          try:
              result = await hb_client.sessions.upload_file(session.id, file_name)

              # or upload the file itself
              # with open(file_name, "rb") as f:
              #    result = await hb_client.sessions.upload_file(session.id, f)

              print("Upload success:", result)

              browser = await connect(browserWSEndpoint=session.ws_endpoint)
              default_context = browser._defaultContext
              page = await default_context.newPage()

              # Navigate to a website
              await page.goto("https://browser-tests-alpha.vercel.app/api/upload-test")
              remote_file_path = result.file_path
              if not remote_file_path:
                  print("Remote file path not found")
                  return

              input = await page.querySelector("#fileUpload")

              if input:
                  await input.uploadFile(remote_file_path)
              else:
                  print("Input element not found")
                  return

              await asyncio.sleep(20)

          except Exception as e:
              print(f"Error: {e}")
          finally:
              await hb_client.sessions.stop(session.id)


      if __name__ == "__main__":
          asyncio.run(main())
      ```
    </CodeGroup>
  </Tab>
</Tabs>
