# File Handling (Downloads & Uploads)

**Browser Swarm** provides robust capabilities for automating file downloads and uploads within your browser sessions. Whether you're scraping data, testing file uploads, or automating workflows, our platform ensures seamless file handling.

***

### 📥 Handling Downloads

#### 🔧 Triggering Downloads

To initiate a file download within a browser session:

1. **Create a browser session** using the SDK or API.
2. **Connect to the session** using your preferred automation framework (e.g., Playwright, Puppeteer, Selenium).
3. **Configure the download behavior** to allow file downloads.
4. **Perform the download action** within your automation script.

Here's an example using Playwright in Node.js:

```javascript
import { chromium } from 'playwright-core';
import { BrowserSwarm } from 'browser-swarm-sdk';

const bs = new BrowserSwarm({ apiKey: process.env.BROWSER_SWARM_API_KEY });

(async () => {
  const session = await bs.sessions.create({
    projectId: process.env.BROWSER_SWARM_PROJECT_ID,
  });

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

  // Set download behavior
  const cdpSession = await context.newCDPSession(page);
  await cdpSession.send('Browser.setDownloadBehavior', {
    behavior: 'allow',
    downloadPath: '/tmp/downloads',
    eventsEnabled: true,
  });

  await page.goto('https://example.com/download');
  await page.click('#download-button');

  // Close session
  await browser.close();
})();
```

#### 📦 Retrieving Downloaded Files

After triggering downloads, you can retrieve the files using the **Session Downloads API**. The files are returned as a ZIP archive.

Here's how to retrieve downloads using Node.js:

```javascript
import fs from 'fs';
import { BrowserSwarm } from 'browser-swarm-sdk';

const bs = new BrowserSwarm({ apiKey: process.env.BROWSER_SWARM_API_KEY });

(async () => {
  const sessionId = 'your-session-id';
  const response = await bs.sessions.downloads.list(sessionId);
  const buffer = await response.arrayBuffer();
  fs.writeFileSync('downloads.zip', Buffer.from(buffer));
})();
```

***

### 📤 Handling Uploads

Uploading files is straightforward with **Browser Swarm**. You can simulate file uploads by setting the file input's value in your automation script.

Here's an example using Playwright in Node.js:

```javascript
import { chromium } from 'playwright-core';
import { BrowserSwarm } from 'browser-swarm-sdk';
import path from 'path';

const bs = new BrowserSwarm({ apiKey: process.env.BROWSER_SWARM_API_KEY });

(async () => {
  const session = await bs.sessions.create({
    projectId: process.env.BROWSER_SWARM_PROJECT_ID,
  });

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

  await page.goto('https://example.com/upload');

  const fileInput = await page.$('input[type="file"]');
  await fileInput.setInputFiles(path.resolve(__dirname, 'file-to-upload.txt'));

  // Submit the form if necessary
  await page.click('#submit-button');

  // Close session
  await browser.close();
})();
```

Ensure that the file path provided to `setInputFiles` is accessible from the environment where your automation script is running.

***

### 💡 Best Practices

* **Download Management**: Always set the download behavior to ensure files are saved correctly during automation.
* **Upload File Paths**: Use absolute paths for files to avoid issues with relative paths, especially in CI/CD environments.
* **Error Handling**: Implement retry logic when retrieving downloads to handle any delays in file availability.
* **Security**: Validate and sanitize file inputs to prevent potential security vulnerabilities during uploads.

***

By leveraging **Browser Swarm's** file handling capabilities, you can automate complex workflows involving file downloads and uploads with ease and reliability.
