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

# 文件上传 API 快速开始

> 几分钟内开始使用文件上传 API，支持多种上传方式

## 欢迎使用文件上传 API

文件上传 API 为您提供灵活、高效的文件上传服务，支持多种上传方式以满足不同的业务需求。无论是远程文件迁移、大文件传输还是小文件快速上传，我们的 API 都能为您提供最佳解决方案。

<CardGroup cols={3}>
  <Card title="Base64 上传" icon="code" href="/cn/file-upload-api/upload-file-base-64">
    Base64 编码文件上传，适合小文件
  </Card>

  <Card title="文件流上传" icon="upload" href="/cn/file-upload-api/upload-file-stream">
    高效的二进制文件流上传，适合大文件
  </Card>

  <Card title="URL 文件上传" icon="link" href="/cn/file-upload-api/upload-file-url">
    从远程 URL 自动下载并上传文件
  </Card>
</CardGroup>

<Info>
  **文件上传是免费的** - 上传文件到我们的服务不收取任何费用。您可以放心上传文件，无需担心上传成本或费用。
</Info>

<Warning>
  **重要提醒**：上传的文件为临时文件，将在 **3天** 后自动删除。请及时下载或迁移重要文件。
</Warning>

## 身份验证

所有 API 请求都需要使用 Bearer 令牌进行身份验证。请从 [API 密钥管理页面](https://sunoapi.org/api-key) 获取您的 API 密钥。

<Warning>
  请妥善保管您的 API 密钥，切勿公开分享。如果怀疑密钥泄露，请立即重置。
</Warning>

### API 基础 URL

```
https://sunoapiorg.redpandaai.co
```

### 身份验证请求头

```http theme={null}
Authorization: Bearer YOUR_API_KEY
```

## 快速开始指南

### 第一步：选择上传方式

根据您的需求选择合适的上传方式：

<Tabs>
  <Tab title="URL 文件上传">
    适用于从远程服务器下载并上传文件：

    <CodeGroup>
      ```bash cURL theme={null}
      curl -X POST "https://sunoapiorg.redpandaai.co/api/file-url-upload" \
        -H "Authorization: Bearer YOUR_API_KEY" \
        -H "Content-Type: application/json" \
        -d '{
          "fileUrl": "https://example.com/sample-image.jpg",
          "uploadPath": "images",
          "fileName": "my-image.jpg"
        }'
      ```

      ```javascript JavaScript theme={null}
      const response = await fetch('https://sunoapiorg.redpandaai.co/api/file-url-upload', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          fileUrl: 'https://example.com/sample-image.jpg',
          uploadPath: 'images',
          fileName: 'my-image.jpg'
        })
      });

      const result = await response.json();
      console.log('上传成功:', result);
      ```

      ```python Python theme={null}
      import requests

      url = "https://sunoapiorg.redpandaai.co/api/file-url-upload"
      headers = {
          "Authorization": "Bearer YOUR_API_KEY",
          "Content-Type": "application/json"
      }

      payload = {
          "fileUrl": "https://example.com/sample-image.jpg",
          "uploadPath": "images",
          "fileName": "my-image.jpg"
      }

      response = requests.post(url, json=payload, headers=headers)
      result = response.json()

      print(f"上传成功: {result}")
      ```
    </CodeGroup>
  </Tab>

  <Tab title="文件流上传">
    适用于直接上传本地文件，特别是大文件：

    <CodeGroup>
      ```bash cURL theme={null}
      curl -X POST "https://sunoapiorg.redpandaai.co/api/file-stream-upload" \
        -H "Authorization: Bearer YOUR_API_KEY" \
        -F "file=@/path/to/your-file.jpg" \
        -F "uploadPath=images/user-uploads" \
        -F "fileName=custom-name.jpg"
      ```

      ```javascript JavaScript theme={null}
      const formData = new FormData();
      formData.append('file', fileInput.files[0]);
      formData.append('uploadPath', 'images/user-uploads');
      formData.append('fileName', 'custom-name.jpg');

      const response = await fetch('https://sunoapiorg.redpandaai.co/api/file-stream-upload', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY'
        },
        body: formData
      });

      const result = await response.json();
      console.log('上传成功:', result);
      ```

      ```python Python theme={null}
      import requests

      url = "https://sunoapiorg.redpandaai.co/api/file-stream-upload"
      headers = {
          "Authorization": "Bearer YOUR_API_KEY"
      }

      files = {
          'file': ('your-file.jpg', open('/path/to/your-file.jpg', 'rb')),
          'uploadPath': (None, 'images/user-uploads'),
          'fileName': (None, 'custom-name.jpg')
      }

      response = requests.post(url, headers=headers, files=files)
      result = response.json()

      print(f"上传成功: {result}")
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Base64 上传">
    适用于 Base64 编码的文件数据：

    <CodeGroup>
      ```bash cURL theme={null}
      curl -X POST "https://sunoapiorg.redpandaai.co/api/file-base64-upload" \
        -H "Authorization: Bearer YOUR_API_KEY" \
        -H "Content-Type: application/json" \
        -d '{
          "base64Data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
          "uploadPath": "images",
          "fileName": "base64-image.png"
        }'
      ```

      ```javascript JavaScript theme={null}
      const response = await fetch('https://sunoapiorg.redpandaai.co/api/file-base64-upload', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          base64Data: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...',
          uploadPath: 'images',
          fileName: 'base64-image.png'
        })
      });

      const result = await response.json();
      console.log('上传成功:', result);
      ```

      ```python Python theme={null}
      import requests
      import base64

      # 读取文件并转换为base64
      with open('/path/to/your-file.jpg', 'rb') as f:
          file_data = base64.b64encode(f.read()).decode('utf-8')
          base64_data = f'data:image/jpeg;base64,{file_data}'

      url = "https://sunoapiorg.redpandaai.co/api/file-base64-upload"
      headers = {
          "Authorization": "Bearer YOUR_API_KEY",
          "Content-Type": "application/json"
      }

      payload = {
          "base64Data": base64_data,
          "uploadPath": "images",
          "fileName": "base64-image.jpg"
      }

      response = requests.post(url, json=payload, headers=headers)
      result = response.json()

      print(f"上传成功: {result}")
      ```
    </CodeGroup>
  </Tab>
</Tabs>

### 第二步：处理响应结果

成功上传后，您将收到包含文件信息的响应：

```json theme={null}
{
  "success": true,
  "code": 200,
  "msg": "文件上传成功",
  "data": {
    "fileId": "file_abc123456",
    "fileName": "my-image.jpg",
    "originalName": "sample-image.jpg",
    "fileSize": 245760,
    "mimeType": "image/jpeg",
    "uploadPath": "images",
    "fileUrl": "https://sunoapiorg.redpandaai.co/files/images/my-image.jpg",
    "downloadUrl": "https://sunoapiorg.redpandaai.co/download/file_abc123456",
    "uploadTime": "2025-01-15T10:30:00Z",
    "expiresAt": "2025-01-18T10:30:00Z"
  }
}
```

## 上传方式对比

选择最适合您需求的上传方式：

<CardGroup cols={3}>
  <Card title="URL 文件上传" icon="link">
    **最适合**：文件迁移、批量处理

    **优势**：

    * 无需本地文件
    * 自动下载处理
    * 支持远程资源

    **限制**：

    * 需要公开可访问的URL
    * 30秒下载超时
    * 推荐≤100MB
  </Card>

  <Card title="文件流上传" icon="upload">
    **最适合**：大文件、本地文件

    **优势**：

    * 高传输效率
    * 支持大文件
    * 二进制传输

    **限制**：

    * 需要本地文件
    * 服务器处理时间
  </Card>

  <Card title="Base64 上传" icon="code">
    **最适合**：小文件、API集成

    **优势**：

    * JSON格式传输
    * 易于集成
    * 支持Data URL

    **限制**：

    * 数据量增加33%
    * 不适合大文件
    * 推荐≤10MB
  </Card>
</CardGroup>

## 实用示例

### 批量文件上传

使用文件流上传处理多个文件：

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    class FileUploadAPI {
      constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseUrl = 'https://sunoapiorg.redpandaai.co';
      }
      
      async uploadFile(file, uploadPath = '', fileName = null) {
        const formData = new FormData();
        formData.append('file', file);
        if (uploadPath) formData.append('uploadPath', uploadPath);
        if (fileName) formData.append('fileName', fileName);
        
        const response = await fetch(`${this.baseUrl}/api/file-stream-upload`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.apiKey}`
          },
          body: formData
        });
        
        if (!response.ok) {
          throw new Error(`上传失败: ${response.statusText}`);
        }
        
        return response.json();
      }
      
      async uploadFromUrl(fileUrl, uploadPath = '', fileName = null) {
        const response = await fetch(`${this.baseUrl}/api/file-url-upload`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            fileUrl,
            uploadPath,
            fileName
          })
        });
        
        if (!response.ok) {
          throw new Error(`上传失败: ${response.statusText}`);
        }
        
        return response.json();
      }
      
      async uploadBase64(base64Data, uploadPath = '', fileName = null) {
        const response = await fetch(`${this.baseUrl}/api/file-base64-upload`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            base64Data,
            uploadPath,
            fileName
          })
        });
        
        if (!response.ok) {
          throw new Error(`上传失败: ${response.statusText}`);
        }
        
        return response.json();
      }
    }

    // 使用示例
    const uploader = new FileUploadAPI('YOUR_API_KEY');

    // 批量上传文件
    async function uploadMultipleFiles(files) {
      const results = [];
      
      for (let i = 0; i < files.length; i++) {
        try {
          const result = await uploader.uploadFile(
            files[i], 
            'user-uploads', 
            `file-${i + 1}-${files[i].name}`
          );
          results.push(result);
          console.log(`文件 ${i + 1} 上传成功:`, result.data.fileUrl);
        } catch (error) {
          console.error(`文件 ${i + 1} 上传失败:`, error.message);
        }
      }
      
      return results;
    }

    // 从URL批量上传
    async function uploadFromUrls(urls) {
      const results = [];
      
      for (let i = 0; i < urls.length; i++) {
        try {
          const result = await uploader.uploadFromUrl(
            urls[i], 
            'downloads', 
            `download-${i + 1}.jpg`
          );
          results.push(result);
          console.log(`URL ${i + 1} 上传成功:`, result.data.fileUrl);
        } catch (error) {
          console.error(`URL ${i + 1} 上传失败:`, error.message);
        }
      }
      
      return results;
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import base64
    import os
    from typing import List, Optional

    class FileUploadAPI:
        def __init__(self, api_key: str):
            self.api_key = api_key
            self.base_url = 'https://sunoapiorg.redpandaai.co'
            self.headers = {
                'Authorization': f'Bearer {api_key}'
            }
        
        def upload_file(self, file_path: str, upload_path: str = '', 
                       file_name: Optional[str] = None) -> dict:
            """文件流上传"""
            files = {
                'file': (os.path.basename(file_path), open(file_path, 'rb'))
            }
            
            data = {}
            if upload_path:
                data['uploadPath'] = upload_path
            if file_name:
                data['fileName'] = file_name
            
            response = requests.post(
                f'{self.base_url}/api/file-stream-upload',
                headers=self.headers,
                files=files,
                data=data
            )
            
            if not response.ok:
                raise Exception(f'上传失败: {response.text}')
            
            return response.json()
        
        def upload_from_url(self, file_url: str, upload_path: str = '', 
                           file_name: Optional[str] = None) -> dict:
            """URL文件上传"""
            payload = {
                'fileUrl': file_url,
                'uploadPath': upload_path,
                'fileName': file_name
            }
            
            response = requests.post(
                f'{self.base_url}/api/file-url-upload',
                headers={**self.headers, 'Content-Type': 'application/json'},
                json=payload
            )
            
            if not response.ok:
                raise Exception(f'上传失败: {response.text}')
            
            return response.json()
        
        def upload_base64(self, base64_data: str, upload_path: str = '', 
                         file_name: Optional[str] = None) -> dict:
            """Base64文件上传"""
            payload = {
                'base64Data': base64_data,
                'uploadPath': upload_path,
                'fileName': file_name
            }
            
            response = requests.post(
                f'{self.base_url}/api/file-base64-upload',
                headers={**self.headers, 'Content-Type': 'application/json'},
                json=payload
            )
            
            if not response.ok:
                raise Exception(f'上传失败: {response.text}')
            
            return response.json()

    # 使用示例
    def main():
        uploader = FileUploadAPI('YOUR_API_KEY')
        
        # 批量上传本地文件
        file_paths = [
            '/path/to/file1.jpg',
            '/path/to/file2.png',
            '/path/to/document.pdf'
        ]
        
        print("开始批量上传文件...")
        for i, file_path in enumerate(file_paths):
            try:
                result = uploader.upload_file(
                    file_path, 
                    'user-uploads', 
                    f'file-{i + 1}-{os.path.basename(file_path)}'
                )
                print(f"文件 {i + 1} 上传成功: {result['data']['fileUrl']}")
            except Exception as e:
                print(f"文件 {i + 1} 上传失败: {e}")
        
        # 批量从URL上传
        urls = [
            'https://example.com/image1.jpg',
            'https://example.com/image2.png'
        ]
        
        print("\n开始从URL批量上传...")
        for i, url in enumerate(urls):
            try:
                result = uploader.upload_from_url(
                    url, 
                    'downloads', 
                    f'download-{i + 1}.jpg'
                )
                print(f"URL {i + 1} 上传成功: {result['data']['fileUrl']}")
            except Exception as e:
                print(f"URL {i + 1} 上传失败: {e}")

    if __name__ == '__main__':
        main()
    ```
  </Tab>
</Tabs>

## 错误处理

常见错误及处理方法：

<AccordionGroup>
  <Accordion title="401 未授权">
    ```javascript theme={null}
    // 检查API密钥是否正确
    if (response.status === 401) {
      console.error('API密钥无效，请检查Authorization头');
      // 重新获取或更新API密钥
    }
    ```
  </Accordion>

  <Accordion title="400 参数错误">
    ```javascript theme={null}
    // 检查请求参数
    if (response.status === 400) {
      const error = await response.json();
      console.error('请求参数错误:', error.msg);
      // 检查必填参数是否提供
      // 检查文件格式是否支持
      // 检查URL是否可访问
    }
    ```
  </Accordion>

  <Accordion title="500 服务器错误">
    ```javascript theme={null}
    // 实施重试机制
    async function uploadWithRetry(uploadFunction, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          return await uploadFunction();
        } catch (error) {
          if (i === maxRetries - 1) throw error;
          
          // 指数退避
          const delay = Math.pow(2, i) * 1000;
          await new Promise(resolve => setTimeout(resolve, delay));
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## 最佳实践

<AccordionGroup>
  <Accordion title="文件大小优化">
    * **小文件** (≤1MB)：推荐使用 Base64 上传
    * **中等文件** (1MB-10MB)：推荐使用文件流上传
    * **大文件** (>10MB)：必须使用文件流上传
    * **远程文件**：使用 URL 上传，注意100MB限制
  </Accordion>

  <Accordion title="文件命名规范">
    * **随机生成**：如不提供fileName参数，系统将自动生成随机文件名
    * **文件覆盖**：若提供的fileName与已存在文件相同，旧文件将被覆盖
    * **缓存行为**：由于缓存机制，文件覆盖效果可能不会立即显现
    * **最佳实践**：建议使用带时间戳的唯一文件名避免冲突（如：`image-2024-01-15-10-30.jpg`）
  </Accordion>

  <Accordion title="性能优化">
    * 实施并发控制，避免同时上传过多文件
    * 对大文件考虑分片上传策略
    * 使用适当的重试机制处理网络问题
    * 监控上传进度并提供用户反馈
  </Accordion>

  <Accordion title="安全考虑">
    * 妥善保管API密钥，定期轮换
    * 验证文件类型和大小
    * 对敏感文件考虑加密传输
    * 及时下载重要文件，避免3天后删除
  </Accordion>

  <Accordion title="错误处理">
    * 实施完整的错误处理逻辑
    * 记录上传日志用于问题排查
    * 提供友好的错误提示给用户
    * 对失败的上传提供重试选项
  </Accordion>
</AccordionGroup>

## 文件存储说明

<Warning>
  **重要提醒**：所有上传的文件均为临时文件，将在上传后 **3天** 自动删除。
</Warning>

* 文件上传后立即可访问和下载
* 文件URL在3天内保持有效
* 系统会在响应中提供 `expiresAt` 字段表示过期时间
* 建议在过期前及时下载或迁移重要文件
* 可以使用 `downloadUrl` 字段获取直接下载链接

## 状态码说明

<ResponseField name="200" type="成功">
  请求已成功处理，文件上传完成
</ResponseField>

<ResponseField name="400" type="参数错误">
  请求参数不正确或缺少必填参数
</ResponseField>

<ResponseField name="401" type="未授权">
  缺少身份验证凭据或凭据无效
</ResponseField>

<ResponseField name="405" type="方法不被允许">
  请求方法不支持，请检查HTTP方法
</ResponseField>

<ResponseField name="500" type="服务器错误">
  处理请求时发生意外错误，请重试或联系支持
</ResponseField>

## 下一步

<CardGroup cols={3}>
  <Card title="URL 文件上传" icon="link" href="/cn/file-upload-api/upload-file-url">
    了解如何从远程URL上传文件
  </Card>

  <Card title="文件流上传" icon="upload" href="/cn/file-upload-api/upload-file-stream">
    学习高效的文件流上传方法
  </Card>

  <Card title="Base64 上传" icon="code" href="/cn/file-upload-api/upload-file-base-64">
    掌握Base64编码文件上传
  </Card>
</CardGroup>

## 支持

<Info>
  需要帮助吗？我们的技术支持团队随时为您提供帮助。

  * **邮箱**: [support@sunoapi.org](mailto:support@sunoapi.org)
  * **文档**: [docs.sunoapi.org](https://docs.sunoapi.org)
  * **API状态**: 查看我们的状态页面了解实时API健康状况
</Info>

***

准备开始上传文件了吗？[获取您的API密钥](https://sunoapi.org/api-key)，立即开始使用文件上传服务！
