# How to Replace a File Without Changing Its Link

> Learn how to update or swap an uploaded file on X02 while keeping the exact same URL and folder settings. Includes simple visual dashboard steps and developer REST API references.

Source: https://x02.me/blog/how-to-replace-file-without-changing-link · 2026-09-01 · X02 Team

We've all been there: you upload a screenshot, publish a guide, send out a PDF report, or post an image link to Discord and Twitter—only to notice a glaring typo, an outdated price tag, or an old UI mockup five minutes later.

On traditional image hosts, fixing this is painful. You have to delete the file, re-upload the new version, get a completely new URL, and then manually edit every tweet, forum post, GitHub readme, or document where the old link was shared. If you don't control the place where the link was posted, you're stuck with a broken link.

**X02 solves this with In-Place File Replacement.** You can swap the underlying file anytime while keeping the exact same public URL, folder placement, and privacy settings.

> [!TIP]
> **Quick Navigation:**
> * [2-Click Dashboard Replacement](#step-by-step-replacing-a-file-from-the-dashboard)
> * [Common Everyday Use Cases](#common-everyday-use-cases)
> * [How It Operates Under the Hood](#1-how-replacement-operates-under-the-hood)
> * [Developer API & Code Examples](#2-replacing-a-file-via-curl-terminal)
> * [Next Steps & Related Tutorials](#next-steps--related-tutorials)

---

## Part 1: The Easy Guide (For Everyone)

You don't need any technical skills to replace a file. You can do it in two clicks directly from your personal dashboard.

![Architecture Diagram](/blog-diagrams/how-to-replace-file-without-changing-link-1.svg)

### What Happens When You Replace a File?
* **Your link stays 100% identical:** Any existing links (`https://x02.me/i/yourfile.png`) or custom subdomain links (`https://yourname.x02.me/i/yourfile.png`) immediately display your new content.
* **Metadata stays intact:** The file's creation date is preserved.
* **Folder & privacy settings don't change:** If the file was in a specific folder or password-protected album, it stays right where you organized it.
* **Old content is permanently erased:** The previous version is completely overwritten in storage.

---

### Step-by-Step: Replacing a File from the Dashboard

| Where to Go | Direct Link | Action |
| :--- | :--- | :--- |
| **`Dashboard`**  **`Gallery`**  `[Hover File Card]` | [Open Dashboard Gallery](https://x02.me/dashboard) | Click **Replace** (Swap Icon) |

1. **Log in** to your account at **[x02.me](https://x02.me)** and go to your **Dashboard**.
2. Find the file you want to update in your **Gallery**.
3. Hover over the file card and click the **Replace** button (or click the file to open the full preview modal and select **Replace** from the menu).
4. Select your new file from your computer.
5. Confirm the swap. 

That's it! In less than two seconds, anyone opening your original link will see the new version.

> [!TIP]
> **Power-User Shortcut:** If you replace files frequently, you can turn on **"Bypass Confirmation"** in your gallery settings to replace files immediately with a single click.

---

### Common Everyday Use Cases

* **Discord & Social Media Announcements:** Fix mistakes in posted event flyers or schedules without deleting and re-sending messages.
* **Documentation & Readmes:** Update software screenshots in GitHub readmes without having to commit new image links to Git history.
* **Resumes & Client Documents:** Update your portfolio or PDF resume while keeping the link you sent to hiring managers active.
* **Live Product Banners:** Swap promotional graphics on websites or forums without editing HTML embed tags.

---

## Part 2: The Developer & Power User Guide

For developers building automated pipelines, release scripts, or dynamic assets, X02 exposes an in-place replacement endpoint over REST API.

---

### 1. How Replacement Operates Under the Hood

When you perform an in-place replacement:
1. **Object Key Persistence:** Rather than generating a new random UUID or slug, the backend retrieves the file's existing storage key (`r2Key` or disk path) and overwrites the binary buffer directly.
2. **Automated Safety Re-Verification:** The newly uploaded binary is asynchronously checked by X02's automated moderation pipeline to ensure it meets platform guidelines.
3. **Database Metadata Delta:** The database recalculates the file size, hash (`SHA-256`), and MIME type, updating your account's storage usage delta while preserving the original upload timestamp.
4. **Cache-Control & Instant Edge Purging:** The asset is served with cache-revalidation headers (`public, max-age=0, s-maxage=31536000, must-revalidate`), prompting intermediate proxies, Cloudflare edge nodes, and browsers to revalidate and serve the new asset immediately.

---

### 2. Replacing a File via cURL (Terminal)

Send a `PATCH` request to `/api/user/images/:filename/replace` with your API key:

```bash
curl -X PATCH "https://x02.me/api/user/images/ABCD123.png/replace" \
  -H "x-api-key: YOUR_X02_API_KEY" \
  -F "file=@/path/to/new-graphic.png"
```

#### Successful JSON Response:
```json
{
  "success": true,
  "message": "File replaced successfully",
  "filename": "ABCD123.png",
  "size": 184520,
  "mimeType": "image/png",
  "url": "https://x02.me/i/ABCD123.png"
}
```

---

### 3. Replacing a File in JavaScript / TypeScript (Node.js)

Automate asset replacements in build scripts or continuous integration workflows:

```typescript
import fs from "fs";

async function replaceHostedFile(filename: string, newFilePath: string, apiKey: string) {
  const formData = new FormData();
  const fileBuffer = fs.readFileSync(newFilePath);
  formData.append("file", new Blob([fileBuffer]), filename);

  const response = await fetch(`https://x02.me/api/user/images/${filename}/replace`, {
    method: "PATCH",
    headers: {
      "x-api-key": apiKey,
      "Accept": "application/json",
    },
    body: formData,
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Failed to replace file: ${error.error || response.statusText}`);
  }

  const result = await response.json();
  console.log("File successfully replaced at:", result.url);
  return result;
}

// Example usage
replaceHostedFile("banner_q3.png", "./assets/banner_q3_final.png", "YOUR_API_KEY")
  .catch(console.error);
```

---

### 4. Replacing a File in Python

A clean Python automation script using `requests`:

```python
import requests

def replace_file(filename: str, new_file_path: str, api_key: str):
    url = f"https://x02.me/api/user/images/{filename}/replace"
    headers = {
        "x-api-key": api_key,
        "Accept": "application/json"
    }

    with open(new_file_path, "rb") as f:
        files = {"file": f}
        response = requests.patch(url, headers=headers, files=files)

    if response.status_code == 200:
        data = response.json()
        print(f"Success! File replaced at: {data['url']}")
        return data
    else:
        print(f"Error ({response.status_code}):", response.text)
        response.raise_for_status()

# Example usage
replace_file("test-build.zip", "./dist/test-build-v2.zip", "YOUR_API_KEY")
```

---

### 5. Replacing Files from a Shell Script

The same endpoint works from a one-liner, which is handy in a deploy step or a cron job that keeps a hosted asset current:

```bash
curl -X PATCH "https://up.x02.me/api/user/images/ABCD123.png/replace"   -H "x-api-key: YOUR_API_KEY"   -F "file=@./updated_screenshot.png"
```

---

## Best Practices & Tips

| Tip | Why It Matters |
|---|---|
| **Match Format When Possible** | While you can swap a `.png` for another `.png`, keeping the file extension consistent prevents client-side rendering issues with static image tags. |
| **Check Storage Limits** | If the replacement file is significantly larger than the old one, ensure your account has sufficient quota to cover the size difference. |
| **Allow a Few Seconds for Global CDN Propagation** | While edge cache headers revalidate immediately, some aggressive browser caches may need a hard refresh (`Ctrl + F5` or `Cmd + Shift + R`). |

---

## Next Steps & Related Tutorials

| What to learn next | Guide Link |
| :--- | :--- |
| **Rename files to clean URLs** | [How to Rename Your Uploaded Files ](/blog/how-to-rename-uploaded-files) |
| **Organize uploads into custom folders** | [How to Organize Files with Folders ](/blog/how-to-organize-files-with-folders) |
| **Connect ShareX for 1-second captures** | [How to Integrate ShareX with X02 ](/blog/how-to-integrate-sharex-with-x02) |
| **Explore all upload channels** | [How to Upload Files to X02 ](/blog/how-to-upload-files-to-x02) |
