You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现CatBox客户端文件上传?若不可行能否用PHP?

Client-Side JavaScript (and PHP) File Uploads for CatBox, file.io, Uguu, put.re

Hey there! Since you're a JS newbie and want to implement client-side file uploads first (with PHP as a backup), let's walk through how to integrate each of your chosen services—starting with your top pick, CatBox.

Client-Side JavaScript Implementation

All these services support browser-based uploads via the Fetch API (modern and easy to read) or XMLHttpRequest. We'll use Fetch with FormData to handle file uploads, which works for most cases.

1. CatBox (Priority Pick)

CatBox has a straightforward API for temporary and long-term file storage. Here's a complete example:

HTML

<input type="file" id="catboxFileInput">
<button onclick="uploadToCatBox()">Upload to CatBox</button>
<p id="catboxResult"></p>

JavaScript

// Using async/await (ES6+)
async function uploadToCatBox() {
  const fileInput = document.getElementById('catboxFileInput');
  const file = fileInput.files[0];
  
  // Check if a file is selected
  if (!file) {
    document.getElementById('catboxResult').textContent = 'Please select a file first!';
    return;
  }

  // Create FormData to wrap the file
  const formData = new FormData();
  formData.append('fileToUpload', file);
  
  // Optional: Add this line to get a long-term link (instead of temporary)
  // formData.append('reqtype', 'longkey');

  try {
    const response = await fetch('https://catbox.moe/user/api.php', {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      throw new Error(`Upload failed with status: ${response.status}`);
    }

    const uploadUrl = await response.text();
    document.getElementById('catboxResult').textContent = `Success! File URL: ${uploadUrl}`;
  } catch (error) {
    document.getElementById('catboxResult').textContent = `Error: ${error.message}`;
  }
}

New-Friendly Note

If async/await feels confusing, you can use .then() syntax instead:

function uploadToCatBox() {
  const fileInput = document.getElementById('catboxFileInput');
  const file = fileInput.files[0];
  if (!file) {
    document.getElementById('catboxResult').textContent = 'Please select a file first!';
    return;
  }

  const formData = new FormData();
  formData.append('fileToUpload', file);

  fetch('https://catbox.moe/user/api.php', { method: 'POST', body: formData })
    .then(response => {
      if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
      return response.text();
    })
    .then(url => document.getElementById('catboxResult').textContent = `Success! URL: ${url}`)
    .catch(err => document.getElementById('catboxResult').textContent = `Error: ${err.message}`);
}

2. file.io

file.io returns JSON responses, so we'll parse that to get the upload link:

async function uploadToFileIO() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  if (!file) { alert('Select a file first!'); return; }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await fetch('https://file.io', {
      method: 'POST',
      body: formData
    });
    const data = await response.json();
    
    if (data.success) {
      alert(`Uploaded! URL: ${data.link}`);
    } else {
      alert(`Error: ${data.message}`);
    }
  } catch (err) {
    alert(`Upload failed: ${err.message}`);
  }
}

3. Uguu

Uguu's API uses a files[] field for uploads and returns JSON with file details:

async function uploadToUguu() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  if (!file) return;

  const formData = new FormData();
  formData.append('files[]', file);

  try {
    const response = await fetch('https://uguu.se/api.php?d=upload-tool', {
      method: 'POST',
      body: formData
    });
    const data = await response.json();
    
    if (data.success) {
      alert(`File URL: https://uguu.se${data.files[0].url}`);
    } else {
      alert(`Error: ${data.error}`);
    }
  } catch (err) {
    alert(`Failed: ${err.message}`);
  }
}

4. put.re

put.re is even simpler—just send the file directly in the request body:

async function uploadToPutRe() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  if (!file) return;

  try {
    const response = await fetch('https://put.re', {
      method: 'POST',
      body: file
    });
    const url = await response.text();
    alert(`Upload successful! URL: ${url}`);
  } catch (err) {
    alert(`Upload failed: ${err.message}`);
  }
}

Key JavaScript Considerations

  • CORS Errors: Most of these services support cross-origin requests (CORS), but if you see a No Access-Control-Allow-Origin error, you'll need to use a PHP backend (see below) as a proxy.
  • File Limits: Each service has max file sizes (e.g., CatBox: 200MB temporary, 100MB long-term). Check their docs for details.
  • Browser Support: Fetch and FormData work in all modern browsers (Chrome, Firefox, Edge, Safari 10.1+).

PHP Backup Implementation

If client-side JS isn't working (e.g., CORS issues), you can use PHP to handle the upload via cURL. Here's how to do it for CatBox:

PHP Code + HTML Form

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
  $uploadedFile = $_FILES['fileToUpload'];

  // Check for upload errors
  if ($uploadedFile['error'] !== UPLOAD_ERR_OK) {
    die("Upload error code: " . $uploadedFile['error']);
  }

  // Prepare file for cURL upload
  $curlFile = new CURLFile(
    $uploadedFile['tmp_name'],
    $uploadedFile['type'],
    $uploadedFile['name']
  );

  $postData = [
    'fileToUpload' => $curlFile,
    // Optional: Uncomment for long-term links
    // 'reqtype' => 'longkey'
  ];

  // Initialize cURL
  $ch = curl_init('https://catbox.moe/user/api.php');
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Execute request and handle response
  $response = curl_exec($ch);
  $curlError = curl_error($ch);
  curl_close($ch);

  if ($curlError) {
    die("cURL error: " . $curlError);
  } else {
    echo "<p>Upload successful! File URL: <strong>$response</strong></p>";
  }
}
?>

<!-- HTML Upload Form -->
<form method="POST" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" required>
  <button type="submit">Upload via PHP</button>
</form>

PHP for Other Services

The structure is similar for file.io, Uguu, and put.re—just adjust the API endpoint and POST fields to match each service's documentation.


内容的提问来源于stack exchange,提问作者Filip Troníček

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:11:33