cloud-storage-web

4
1
Source

Complete guide for CloudBase cloud storage using Web SDK (@cloudbase/js-sdk) - upload, download, temporary URLs, file management, and best practices.

Install

mkdir -p .claude/skills/cloud-storage-web && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3544" && unzip -o skill.zip -d .claude/skills/cloud-storage-web && rm skill.zip

Installs to .claude/skills/cloud-storage-web

About this skill

Cloud Storage Web SDK

Use this skill when building web applications that need to upload, download, or manage files using CloudBase cloud storage via the @cloudbase/js-sdk (Web SDK).

When to use this skill

Use this skill for file storage operations in web applications when you need to:

  • Upload files from web browsers to CloudBase cloud storage
  • Generate temporary download URLs for stored files
  • Delete files from cloud storage
  • Download files from cloud storage to local browser

Do NOT use for:

  • Mini-program file operations (use mini-program specific skills)
  • Backend file operations (use Node SDK skills)
  • Database operations (use database skills)

How to use this skill (for a coding agent)

  1. Initialize CloudBase SDK

    • Ask the user for their CloudBase environment ID
    • Always use the standard initialization pattern shown below
  2. Choose the right storage method

    • uploadFile - For uploading files from browser to cloud storage
    • getTempFileURL - For generating temporary download links
    • deleteFile - For deleting files from storage
    • downloadFile - For downloading files to browser
  3. Handle CORS requirements

    • Remind users to add their domain to CloudBase console security domains
    • This prevents CORS errors during file operations
  4. Follow file path rules

    • Use valid characters: [0-9a-zA-Z], /, !, -, _, ., , *, Chinese characters
    • Use / for folder structure (e.g., folder/file.jpg)

SDK Initialization

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
  env: "your-env-id", // Replace with your CloudBase environment ID
});

Initialization rules:

  • Always use synchronous initialization with the pattern above
  • Do not lazy-load the SDK with dynamic imports
  • Keep a single shared app instance across your application

File Upload (uploadFile)

Basic Usage

const result = await app.uploadFile({
  cloudPath: "folder/filename.jpg", // File path in cloud storage
  filePath: fileInput.files[0],     // HTML file input element
});

// Result contains:
{
  fileID: "cloud://env-id/folder/filename.jpg", // Unique file identifier
  // ... other metadata
}

Advanced Upload with Progress

const result = await app.uploadFile({
  cloudPath: "uploads/avatar.jpg",
  filePath: selectedFile,
  method: "put", // "post" or "put" (default: "put")
  onUploadProgress: (progressEvent) => {
    const percent = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
    console.log(`Upload progress: ${percent}%`);
    // Update UI progress bar here
  }
});

Parameters

ParameterTypeRequiredDescription
cloudPathstringYesAbsolute path with filename (e.g., "folder/file.jpg")
filePathFileYesHTML file input object
method"post" | "put"NoUpload method (default: "put")
onUploadProgressfunctionNoProgress callback function

Cloud Path Rules

  • Valid characters: [0-9a-zA-Z], /, !, -, _, ., , *, Chinese characters
  • Invalid characters: Other special characters
  • Structure: Use / to create folder hierarchy
  • Examples:
    • "avatar.jpg"
    • "uploads/avatar.jpg"
    • "user/123/avatar.jpg"

CORS Configuration

⚠️ IMPORTANT: To prevent CORS errors, add your domain to CloudBase console:

  1. Go to CloudBase Console → Environment → Security Sources → Security Domains
  2. Add your frontend domain (e.g., https://your-app.com, http://localhost:3000)
  3. If CORS errors occur, remove and re-add the domain

Temporary Download URLs (getTempFileURL)

Basic Usage

const result = await app.getTempFileURL({
  fileList: [
    {
      fileID: "cloud://env-id/folder/filename.jpg",
      maxAge: 3600 // URL valid for 1 hour (seconds)
    }
  ]
});

// Access the download URL
result.fileList.forEach(file => {
  if (file.code === "SUCCESS") {
    console.log("Download URL:", file.tempFileURL);
    // Use this URL to download or display the file
  }
});

Multiple Files

const result = await app.getTempFileURL({
  fileList: [
    {
      fileID: "cloud://env-id/image1.jpg",
      maxAge: 7200 // 2 hours
    },
    {
      fileID: "cloud://env-id/document.pdf",
      maxAge: 86400 // 24 hours
    }
  ]
});

Parameters

ParameterTypeRequiredDescription
fileListArrayYesArray of file objects

fileList Item Structure

ParameterTypeRequiredDescription
fileIDstringYesCloud storage file ID
maxAgenumberYesURL validity period in seconds

Response Structure

{
  code: "SUCCESS",
  fileList: [
    {
      code: "SUCCESS",
      fileID: "cloud://env-id/folder/filename.jpg",
      tempFileURL: "https://temporary-download-url"
    }
  ]
}

Best Practices

  • Set appropriate maxAge based on use case (1 hour to 24 hours)
  • Handle SUCCESS/ERROR codes in response
  • Use temporary URLs for private file access
  • Cache URLs if needed, but respect expiration time

File Deletion (deleteFile)

Basic Usage

const result = await app.deleteFile({
  fileList: [
    "cloud://env-id/folder/filename.jpg"
  ]
});

// Check deletion results
result.fileList.forEach(file => {
  if (file.code === "SUCCESS") {
    console.log("File deleted:", file.fileID);
  } else {
    console.error("Failed to delete:", file.fileID);
  }
});

Multiple Files

const result = await app.deleteFile({
  fileList: [
    "cloud://env-id/old-avatar.jpg",
    "cloud://env-id/temp-upload.jpg",
    "cloud://env-id/cache-file.dat"
  ]
});

Parameters

ParameterTypeRequiredDescription
fileListArray<string>YesArray of file IDs to delete

Response Structure

{
  fileList: [
    {
      code: "SUCCESS",
      fileID: "cloud://env-id/folder/filename.jpg"
    }
  ]
}

Best Practices

  • Always check response codes before assuming deletion success
  • Use this for cleanup operations (old avatars, temp files, etc.)
  • Consider batching multiple deletions for efficiency

File Download (downloadFile)

Basic Usage

const result = await app.downloadFile({
  fileID: "cloud://env-id/folder/filename.jpg"
});

// File is downloaded to browser default download location

Parameters

ParameterTypeRequiredDescription
fileIDstringYesCloud storage file ID

Response Structure

{
  // Success response (no specific data returned)
  // File is downloaded to browser
}

Best Practices

  • Use for user-initiated downloads (save file dialogs)
  • For programmatic file access, use getTempFileURL instead
  • Handle download errors appropriately

Error Handling

All storage operations should include proper error handling:

try {
  const result = await app.uploadFile({
    cloudPath: "uploads/file.jpg",
    filePath: selectedFile
  });

  if (result.code) {
    // Handle error
    console.error("Upload failed:", result.message);
  } else {
    // Success
    console.log("File uploaded:", result.fileID);
  }
} catch (error) {
  console.error("Storage operation failed:", error);
}

Common Error Codes

  • INVALID_PARAM - Invalid parameters
  • PERMISSION_DENIED - Insufficient permissions
  • RESOURCE_NOT_FOUND - File not found
  • SYS_ERR - System error

Best Practices

  1. File Organization: Use consistent folder structures (uploads/, avatars/, documents/)
  2. Naming Conventions: Use descriptive filenames with timestamps if needed
  3. Progress Feedback: Show upload progress for better UX
  4. Cleanup: Delete temporary/unused files to save storage costs
  5. Security: Validate file types and sizes before upload
  6. Caching: Cache download URLs appropriately but respect expiration
  7. Batch Operations: Use arrays for multiple file operations when possible

Performance Considerations

  1. File Size Limits: Be aware of CloudBase file size limits
  2. Concurrent Uploads: Limit concurrent uploads to prevent browser overload
  3. Progress Monitoring: Use progress callbacks for large file uploads
  4. Temporary URLs: Generate URLs only when needed, with appropriate expiration

Security Considerations

  1. Domain Whitelisting: Always configure security domains to prevent CORS issues
  2. Access Control: Use appropriate file permissions (public vs private)
  3. URL Expiration: Set reasonable expiration times for temporary URLs
  4. User Permissions: Ensure users can only access their own files when appropriate

miniprogram-development

TencentCloudBase

WeChat Mini Program development rules. Use this skill when developing WeChat mini programs, integrating CloudBase capabilities, and deploying mini program projects.

6425

spec-workflow

TencentCloudBase

Standard software engineering workflow for requirement analysis, technical design, and task planning. Use this skill when developing new features, complex architecture designs, multi-module integrations, or projects involving database/UI design.

867

web-development

TencentCloudBase

Web frontend project development rules. Use this skill when developing web frontend pages, deploying static hosting, and integrating CloudBase Web SDK.

105

ai-model-nodejs

TencentCloudBase

Use this skill when developing Node.js backend services or CloudBase cloud functions (Express/Koa/NestJS, serverless, backend APIs) that need AI capabilities. Features text generation (generateText), streaming (streamText), AND image generation (generateImage) via @cloudbase/node-sdk ≥3.16.0. Built-in models include Hunyuan (hunyuan-2.0-instruct-20251111 recommended), DeepSeek (deepseek-v3.2 recommended), and hunyuan-image for images. This is the ONLY SDK that supports image generation. NOT for browser/Web apps (use ai-model-web) or WeChat Mini Program (use ai-model-wechat).

63

cloudbase-document-database-in-wechat-miniprogram

TencentCloudBase

Use CloudBase document database WeChat MiniProgram SDK to query, create, update, and delete data. Supports complex queries, pagination, aggregation, and geolocation queries.

61

auth-web-cloudbase

TencentCloudBase

CloudBase Web Authentication Quick Guide - Provides concise and practical Web frontend authentication solutions with multiple login methods and complete user management.

51

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5721,370

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,1161,191

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4181,109

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,194748

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,154684

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,313614

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.