cloudinary-react
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudinary React Skill
Cloudinary React 技能
When to Use
使用场景
- When a user is building or debugging Cloudinary in a React app (Vite, Create React App, Parcel, etc.).
- When implementing or fixing: Upload Widget, AdvancedImage/AdvancedVideo, transformations, overlays, image galleries, video player, or signed/unsigned uploads.
- When the user sees errors like "createUploadWidget is not a function", wrong imports from , upload preset issues, or video player DOM errors.
@cloudinary/url-gen
- 当用户在React应用(Vite、Create React App、Parcel等)中集成或调试Cloudinary时。
- 当需要实现或修复以下功能时:上传组件、AdvancedImage/AdvancedVideo、媒体转换、叠加层、图片画廊、视频播放器、签名/未签名上传。
- 当用户遇到如下错误时:"createUploadWidget is not a function"、导入错误、上传预设问题、视频播放器DOM错误。
@cloudinary/url-gen
Quick Start
快速开始
Most common operations:
- Setup: Create config file with instance (see Project setup section)
cld - Display image:
const img = cld.image('id').resize(fill().width(800)); <AdvancedImage cldImg={img} /> - Upload Widget: Script in index.html + poll for in useEffect
createUploadWidget - Image overlay: Use or
source(text(...))- see Import reference table for exact pathssource(image(...)) - Signed uploads: See references/signed-uploads.md
- Troubleshooting: See references/troubleshooting.md
For TypeScript: See references/typescript-patterns.md
For Video Player: See references/video-player.md
最常用操作:
- 初始化配置:创建包含实例的配置文件(见项目初始化章节)
cld - 展示图片:
const img = cld.image('id').resize(fill().width(800)); <AdvancedImage cldImg={img} /> - 上传组件:在index.html中引入脚本 + 在useEffect中轮询等待加载完成
createUploadWidget - 图片叠加层:使用或
source(text(...))—— 参考导入对照表获取准确导入路径source(image(...)) - 签名上传:查看 references/signed-uploads.md
- 问题排查:查看 references/troubleshooting.md
TypeScript相关:查看 references/typescript-patterns.md
视频播放器相关:查看 references/video-player.md
Instructions
使用说明
When helping with Cloudinary in React, follow the patterns and rules below. Use the exact import paths and code patterns specified; do not guess subpaths or invent APIs.
当协助解决React中Cloudinary相关问题时,请遵循以下模式和规则。严格使用指定的导入路径和代码模式,不要猜测子路径或自创API。
Cloudinary React SDK Patterns & Common Errors
Cloudinary React SDK 模式与常见错误
Scope: These rules apply to React (web) with the browser Upload Widget. The default is Vite (create-cloudinary-react uses Vite). They also work with other bundlers (Create React App, Next.js, Parcel, etc.): only how you read env vars changes; see "Other bundlers (non-Vite)" below. Rules-only users: see "Project setup (rules-only / without CLI)" for the reusable Cloudinary instance, env, Upload Widget (unsigned/signed), and video player. For React Native uploads (including signed upload), see: https://cloudinary.com/documentation/react_native_image_and_video_upload#signed_upload — same "never expose secret, generate signature on backend" principle, but React Native uses the method and backend SDKs differently.
upload()适用范围:这些规则适用于React(网页端)搭配浏览器端上传组件的场景,默认适配Vite(create-cloudinary-react默认使用Vite),也适用于其他打包工具(Create React App、Next.js、Parcel等):仅环境变量的读取方式有差异,见下文**"其他打包工具(非Vite)"章节。仅使用规则的用户:查看"项目初始化(仅用规则/不使用CLI)"获取可复用的Cloudinary实例、环境变量配置、上传组件(签名/未签名)和视频播放器配置。如果是React Native**上传(包含签名上传),请查看:https://cloudinary.com/documentation/react_native_image_and_video_upload#signed_upload —— 遵循相同的"永远不要暴露密钥,在后端生成签名"原则,但React Native使用的方法和后端SDK的用法有差异。
upload()Official Documentation
官方文档
For complete API references and all configuration options, consult the Cloudinary documentation via llms.txt: https://cloudinary.com/documentation/llms.txt
This skill provides React patterns and common errors. For detailed API options (e.g., all Upload Widget config properties, Video Player API methods), use the documentation markdown files available through llms.txt.
如需完整的API参考和所有配置选项,请通过llms.txt查阅Cloudinary官方文档:https://cloudinary.com/documentation/llms.txt
本技能提供React相关的使用模式和常见错误解决方案。如需详细的API选项(例如上传组件的所有配置属性、视频播放器的API方法),请使用llms.txt提供的markdown格式文档。
Key References
核心参考
- Transformation Rules: https://cloudinary.com/documentation/cloudinary_transformation_rules.md
- Transformation Reference: https://cloudinary.com/documentation/transformation_reference.md
- React Image Transformations & Plugins: https://cloudinary.com/documentation/react_image_transformations.md#plugins
- React Video Transformations: https://cloudinary.com/documentation/react_video_transformations.md
- Upload Widget Reference (complete config options): https://cloudinary.com/documentation/upload_widget_reference.md
- Upload Widget (signed uploads): https://cloudinary.com/documentation/upload_widget.md#signed_uploads
- Cloudinary Video Player (standalone player): https://cloudinary.com/documentation/cloudinary_video_player.md
- Video Player API Reference (complete API methods): https://cloudinary.com/documentation/video_player_api_reference.md
- Video Player React Tutorial: https://cloudinary.com/documentation/video_player_react_tutorial.md
- Upload assets in Next.js (backend signature): https://cloudinary.com/documentation/upload_assets_in_nextjs_tutorial.md
- Cloudinary Node.js SDK (server-side signing) — use v2: ; do not use v1 (e.g. 1.47.0). https://cloudinary.com/documentation/node_integration.md
import { v2 as cloudinary } from 'cloudinary' - React Native image and video upload (signed): https://cloudinary.com/documentation/react_native_image_and_video_upload.md#signed_upload
- Always consult the official transformation rules when creating transformations
- Use only officially supported parameters from the transformation reference
Golden rule for @cloudinary/url-gen: When generating overlay or transformation code, use only the "Import reference" table and "Canonical overlay block" in these rules. Copy those import paths and usage patterns exactly; do not guess or derive paths (e.g. and are from , not ; is from , not ).
textimagequalifiers/sourceactions/overlayPositionqualifiers/positionpositioning/Position- 转换规则:https://cloudinary.com/documentation/cloudinary_transformation_rules.md
- 转换参考:https://cloudinary.com/documentation/transformation_reference.md
- React 图片转换与插件:https://cloudinary.com/documentation/react_image_transformations.md#plugins
- React 视频转换:https://cloudinary.com/documentation/react_video_transformations.md
- 上传组件参考(完整配置选项):https://cloudinary.com/documentation/upload_widget_reference.md
- 上传组件(签名上传):https://cloudinary.com/documentation/upload_widget.md#signed_uploads
- Cloudinary 视频播放器(独立播放器):https://cloudinary.com/documentation/cloudinary_video_player.md
- 视频播放器API参考(完整API方法):https://cloudinary.com/documentation/video_player_api_reference.md
- 视频播放器React教程:https://cloudinary.com/documentation/video_player_react_tutorial.md
- Next.js中上传资源(后端签名):https://cloudinary.com/documentation/upload_assets_in_nextjs_tutorial.md
- Cloudinary Node.js SDK(服务端签名) —— 使用v2版本:;不要使用v1版本(例如1.47.0)。https://cloudinary.com/documentation/node_integration.md
import { v2 as cloudinary } from 'cloudinary' - React Native 图片和视频上传(签名版):https://cloudinary.com/documentation/react_native_image_and_video_upload.md#signed_upload
- 编写转换逻辑时请始终参考官方转换规则
- 仅使用转换参考中官方支持的参数
@cloudinary/url-gen黄金规则:生成叠加层或转换代码时,仅使用本规则中的「导入对照表」和「标准叠加层代码块」,严格复制导入路径和使用模式,不要猜测或推导路径(例如和从导入,而非;从导入,而非)。
textimagequalifiers/sourceactions/overlayPositionqualifiers/positionpositioning/Position📋 PATTERNS (How to Do It Right)
📋 最佳实践模式(正确实现方式)
Project setup (rules-only / without CLI)
项目初始化(仅用规则/不使用CLI)
If the user is not using the create-cloudinary-react CLI and only has these rules, generate the following so they get correct config, env, and widget setup.
1. Environment (.env)
Create a file in the project root with Vite prefix (required for client access):
Create a
.env- (required — use your actual cloud name, never the literal string
VITE_CLOUDINARY_CLOUD_NAME_=my_cloudwhich causes 401)your_cloud_name - (optional; required for unsigned upload widget — use your actual preset name)
VITE_CLOUDINARY_UPLOAD_PRESET=my_preset - Restart the dev server after adding or changing . Use
.envin code, notimport.meta.env.VITE_*.process.env - If env var still empty in browser after restart: Vite may cache the old value. Clear , restart dev server, and do a hard refresh (Cmd+Shift+R / Ctrl+Shift+F5). If still empty, see "Vite env not reaching client" in Common Errors.
node_modules/.vite/
2. Reusable Cloudinary instance (config)
Create a config file (e.g.) so the rest of the app can use a single instance:
Create a config file (e.g.
src/cloudinary/config.tscldts
import { Cloudinary } from '@cloudinary/url-gen';
const cloudName = import.meta.env.VITE_CLOUDINARY_CLOUD_NAME;
if (!cloudName) {
throw new Error('VITE_CLOUDINARY_CLOUD_NAME is not set. Add it to .env with the VITE_ prefix.');
}
export const cld = new Cloudinary({ cloud: { cloudName } });
export const uploadPreset = import.meta.env.VITE_CLOUDINARY_UPLOAD_PRESET || '';- Use this pattern for the reusable instance. Everywhere else: (or the path the user chose) and call
import { cld } from './cloudinary/config'/cld.image(publicId).cld.video(publicId)
3. Upload Widget (unsigned, from scratch)
Strict pattern (always follow this exactly):
- Script in (required): Add
index.htmlto<script src="https://upload-widget.cloudinary.com/global/all.js" async></script>. Do not rely only on dynamic script injection from React — it's fragile.index.html - Poll in useEffect (required): In , poll with
useEffect(e.g. every 100ms) untilsetInterval. Only then create the widget. A single check (even intypeof window.cloudinary?.createUploadWidget === 'function') is not reliable becauseonloadcan exist beforewindow.cloudinaryis attached.createUploadWidget - Add a timeout: Set a timeout (e.g. 10 seconds) to stop polling and show an error if the script never loads. Clear both interval and timeout in cleanup.
- Create widget once: When is available, create the widget and store it in a ref. Clear the interval and timeout. Pass options:
createUploadWidget.{ cloudName, uploadPreset, sources: ['local', 'camera', 'url'], multiple: false } - Open on click: Attach a click listener to a button that calls . Remove the listener in useEffect cleanup.
widgetRef.current?.open()
❌ Do NOT: Check only (not enough); do a single check in (unreliable); skip the script in ; poll forever without a timeout.
window.cloudinaryonloadindex.html- Signed uploads: Do not use only ; use the pattern under "Secure (Signed) Uploads" (uploadSignature as function, fetch api_key, server includes upload_preset in signature).
uploadPreset
4. Video player
- Use imperative video element only (create with document.createElement, append to container ref, pass to videoPlayer). See "Cloudinary Video Player (The Player)" for the full pattern.
5. Summary for rules-only users
- Env: Use your bundler's client env prefix and access (Vite: +
VITE_; see "Other bundlers" if not Vite).import.meta.env.VITE_* - Reusable instance: One config file that creates and exports (and optionally
cld) fromuploadPreset; use it everywhere.@cloudinary/url-gen - Upload widget: Script in index.html (required); in useEffect, poll until is a function, then create widget once and store in ref; unsigned = cloudName + uploadPreset; signed = use uploadSignature function and backend.
createUploadWidget - Video player: Imperative video element (createElement, append to container ref, pass to videoPlayer); dispose + removeChild in cleanup; fall back to AdvancedVideo if init fails.
If the user is not using Vite: Use their bundler's client env prefix and access in the config file and everywhere you read env. Examples: Create React App → , ; Next.js (client) → , . The rest (cld instance, widget options, video player) is the same.
REACT_APP_CLOUDINARY_CLOUD_NAMEprocess.env.REACT_APP_CLOUDINARY_CLOUD_NAMENEXT_PUBLIC_CLOUDINARY_CLOUD_NAMEprocess.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME如果用户不使用create-cloudinary-react CLI,仅遵循本规则,请生成以下配置,确保他们得到正确的配置、环境变量和组件初始化方式。
1. 环境变量(.env)
在项目根目录创建文件,使用Vite前缀(客户端访问必需):
在项目根目录创建
.env- (必填 —— 替换为你实际的云名称,永远不要使用字面量
VITE_CLOUDINARY_CLOUD_NAME_=my_cloud,会导致401错误)your_cloud_name - (可选,未签名上传组件必填 —— 替换为你实际的预设名称)
VITE_CLOUDINARY_UPLOAD_PRESET=my_preset - 添加或修改后重启开发服务。代码中使用
.env读取变量,不要用import.meta.env.VITE_*。process.env - 如果重启后浏览器中环境变量仍然为空:Vite可能缓存了旧值,删除目录,重启开发服务,然后强制刷新页面(Cmd+Shift+R / Ctrl+Shift+F5)。如果仍然为空,查看常见错误中的「Vite环境变量未传递到客户端」章节。
node_modules/.vite/
2. 可复用Cloudinary实例(配置)
创建配置文件(例如),让应用其他部分可以复用同一个实例:
创建配置文件(例如
src/cloudinary/config.tscldts
import { Cloudinary } from '@cloudinary/url-gen';
const cloudName = import.meta.env.VITE_CLOUDINARY_CLOUD_NAME;
if (!cloudName) {
throw new Error('VITE_CLOUDINARY_CLOUD_NAME is not set. Add it to .env with the VITE_ prefix.');
}
export const cld = new Cloudinary({ cloud: { cloudName } });
export const uploadPreset = import.meta.env.VITE_CLOUDINARY_UPLOAD_PRESET || '';- 请使用此模式创建可复用实例,其他地方直接导入:(或用户自定义的路径),然后调用
import { cld } from './cloudinary/config'/cld.image(publicId)即可。cld.video(publicId)
3. 上传组件(未签名版,从零实现)
严格遵循以下模式:
- 在中引入脚本(必填):添加
index.html到<script src="https://upload-widget.cloudinary.com/global/all.js" async></script>中。不要仅依赖React动态注入脚本,这种方式不稳定。index.html - 在useEffect中轮询检测(必填):在中使用
useEffect(例如每100ms检测一次),直到setInterval时再创建组件。仅做单次检测(即使是在typeof window.cloudinary?.createUploadWidget === 'function中)不可靠,因为onload可能在window.cloudinary挂载前就已经存在。createUploadWidget - 添加超时逻辑:设置超时时间(例如10秒),如果脚本始终未加载完成则停止轮询并展示错误。在清理函数中同时清除定时器和超时器。
- 仅创建一次组件:当可用时,创建组件并存入ref中,清除定时器和超时器。传入选项:
createUploadWidget。{ cloudName, uploadPreset, sources: ['local', 'camera', 'url'], multiple: false } - 点击触发打开:给按钮绑定点击事件,调用。在useEffect清理函数中移除事件监听。
widgetRef.current?.open()
❌ 禁止操作:仅检测(不充分);仅在中做单次检测(不可靠);不在中引入脚本;无超时无限轮询。
window.cloudinaryonloadindex.html- 签名上传:不要仅使用,请使用「安全(签名)上传」章节的模式(uploadSignature作为函数,后端返回api_key,签名中包含upload_preset)。
uploadPreset
4. 视频播放器
- 仅使用命令式创建video元素(用document.createElement创建,追加到容器ref中,再传入videoPlayer)。完整模式见「Cloudinary视频播放器」章节。
5. 仅用规则的用户总结
- 环境变量:使用你所用打包工具的客户端环境变量前缀和读取方式(Vite:前缀 +
VITE_;非Vite查看「其他打包工具」章节)。import.meta.env.VITE_* - 可复用实例:在一个配置文件中从创建并导出
@cloudinary/url-gen(可选导出cld),全局复用。uploadPreset - 上传组件:必须在index.html中引入脚本;在useEffect中轮询直到是函数,然后创建一次组件存入ref;未签名版 = cloudName + uploadPreset;签名版 = 使用uploadSignature函数 + 后端支持。
createUploadWidget - 视频播放器:命令式创建video元素(createElement,追加到容器ref,传入videoPlayer);清理时dispose + removeChild;如果初始化失败回退到AdvancedVideo。
如果用户不使用Vite:在配置文件和所有读取环境变量的地方使用对应打包工具的客户端前缀和读取方式。示例:Create React App → ,;Next.js(客户端)→ ,。其他部分(cld实例、组件选项、视频播放器)完全一致。
REACT_APP_CLOUDINARY_CLOUD_NAMEprocess.env.REACT_APP_CLOUDINARY_CLOUD_NAMENEXT_PUBLIC_CLOUDINARY_CLOUD_NAMEprocess.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAMEEnvironment Variables
环境变量
- Default: Vite — Vite requires prefix; use
VITE_(notimport.meta.env.VITE_CLOUDINARY_CLOUD_NAME). Restart dev server after changingprocess.env..env - ✅ CORRECT (Vite): in
VITE_CLOUDINARY_CLOUD_NAME=mycloud;.envimport.meta.env.VITE_CLOUDINARY_CLOUD_NAME - ❌ WRONG: — Never use the literal placeholder
VITE_CLOUDINARY_CLOUD_NAME=your_cloud_name; it causes 401 errors. Use your actual cloud name from the Cloudinary dashboard.your_cloud_name - ⚠️ Vite env not reaching client: If is still
import.meta.env.VITE_CLOUDINARY_CLOUD_NAMEin the browser after restarting:undefined- Clear Vite cache: (or delete
rm -rf node_modules/.vite/folder)node_modules/.vite - Restart dev server:
npm run dev - Hard refresh browser: Cmd+Shift+R (Mac) or Ctrl+Shift+F5 (Windows/Linux)
- If still empty, use a static config workaround (create a with a hardcoded cloud name for dev, then switch back to env later) and see Common Errors → "VITE_ prefix required or env var is undefined"
cloudinaryConfig.ts
- Clear Vite cache:
- 默认:Vite —— Vite要求环境变量带前缀,使用
VITE_读取(不要用import.meta.env.VITE_CLOUDINARY_CLOUD_NAME)。修改process.env后重启开发服务。.env - ✅ 正确用法(Vite):中写
.env;代码中用VITE_CLOUDINARY_CLOUD_NAME=mycloud读取import.meta.env.VITE_CLOUDINARY_CLOUD_NAME - ❌ 错误用法:—— 永远不要使用字面量占位符
VITE_CLOUDINARY_CLOUD_NAME=your_cloud_name,会导致401错误,请替换为Cloudinary控制台中实际的云名称。your_cloud_name - ⚠️ Vite环境变量未传递到客户端:如果重启后浏览器中仍然是
import.meta.env.VITE_CLOUDINARY_CLOUD_NAME:undefined- 清除Vite缓存:(或手动删除
rm -rf node_modules/.vite/文件夹)node_modules/.vite - 重启开发服务:
npm run dev - 强制刷新浏览器:Mac按Cmd+Shift+R,Windows/Linux按Ctrl+Shift+F5
- 如果仍然为空,使用静态配置临时解决(创建硬编码云名称用于开发,后续再切回环境变量),并查看常见错误 → 「需要VITE_前缀或环境变量未定义」章节
cloudinaryConfig.ts
- 清除Vite缓存:
Other bundlers (non-Vite)
其他打包工具(非Vite)
- Only the env access changes. All other patterns (reusable , Upload Widget, Video Player, overlays, signed uploads) are bundler-agnostic.
cld - Create React App: Prefix ; access
REACT_APP_,process.env.REACT_APP_CLOUDINARY_CLOUD_NAME. Restart dev server afterprocess.env.REACT_APP_CLOUDINARY_UPLOAD_PRESETchanges..env - Next.js (client): Prefix for client; access
NEXT_PUBLIC_, etc. Server-side can useprocess.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAMEwithoutprocess.env.CLOUDINARY_*.NEXT_PUBLIC_ - Parcel / other: Check the bundler's docs for "exposing environment variables to the client" (often a prefix or allowlist). Use that prefix and the documented access (e.g. ).
process.env.* - Config file: In (or equivalent), read cloud name and upload preset using the user's bundler env API (e.g. for CRA:
src/cloudinary/config.ts). Sameprocess.env.REACT_APP_CLOUDINARY_CLOUD_NAMEand exports; only the env read line changes.new Cloudinary({ cloud: { cloudName } })
- 仅环境变量的读取方式有变化,其他所有模式(可复用实例、上传组件、视频播放器、叠加层、签名上传)都和打包工具无关。
cld - Create React App:前缀为;使用
REACT_APP_、process.env.REACT_APP_CLOUDINARY_CLOUD_NAME读取。修改process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET后重启开发服务。.env - Next.js(客户端):客户端使用的环境变量前缀为;使用
NEXT_PUBLIC_等读取。服务端可以直接使用process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,不需要process.env.CLOUDINARY_*前缀。NEXT_PUBLIC_ - Parcel / 其他打包工具:查看打包工具文档中「向客户端暴露环境变量」的说明(通常需要前缀或白名单),使用对应前缀和文档中的读取方式(例如)。
process.env.* - 配置文件:在(或等效路径)中,使用用户所用打包工具的环境变量API读取云名称和上传预设(例如CRA用
src/cloudinary/config.ts)。process.env.REACT_APP_CLOUDINARY_CLOUD_NAME和导出逻辑完全一致,仅读取环境变量的行有变化。new Cloudinary({ cloud: { cloudName } })
Upload Presets
上传预设
- Unsigned = client-only uploads (no backend). Signed = backend required, more secure. See "Signed vs unsigned uploads" below for when to use which.
- ✅ Create unsigned upload preset (for simple client uploads): https://console.cloudinary.com/app/settings/upload/presets
- ✅ Set preset in :
.envVITE_CLOUDINARY_UPLOAD_PRESET=your-preset-name - ✅ Use in code:
import { uploadPreset } from './cloudinary/config' - ⚠️ If upload preset is missing, the Upload Widget will show an error message
- ⚠️ Upload presets must be set to "Unsigned" mode for client-side usage (no API key/secret needed)
- When unsigned upload fails: First check that the user configured their upload preset:
- Is set in
VITE_CLOUDINARY_UPLOAD_PRESET? (must match preset name exactly).env - Does the preset exist in the dashboard under Settings → Upload → Upload presets?
- Is the preset set to Unsigned (not Signed)?
- Was the dev server restarted after adding/updating ?
.env
- Is
- 未签名版 = 纯客户端上传(不需要后端)。签名版 = 需要后端支持,安全性更高。何时使用见下文「签名vs未签名上传」章节。
- ✅ 创建未签名上传预设(用于简单的客户端上传):https://console.cloudinary.com/app/settings/upload/presets
- ✅ 在中设置预设:
.envVITE_CLOUDINARY_UPLOAD_PRESET=your-preset-name - ✅ 代码中使用:
import { uploadPreset } from './cloudinary/config' - ⚠️ 如果缺失上传预设,上传组件会展示错误信息
- ⚠️ 客户端使用的上传预设必须设置为「未签名」模式(不需要API密钥/secret)
- 未签名上传失败时:首先检查用户是否正确配置了上传预设:
- 中是否设置了
.env?(必须和预设名称完全匹配)VITE_CLOUDINARY_UPLOAD_PRESET - 控制台的设置 → 上传 → 上传预设中是否存在该预设?
- 预设是否设置为未签名(不是签名)模式?
- 添加/更新后是否重启了开发服务?
.env
Installing Cloudinary packages
安装Cloudinary依赖包
- ✅ Install the latest: When adding Cloudinary packages, use with no version so npm installs the latest compatible version (e.g.
npm install <package>). In package.json use a caret range (e.g.npm install cloudinary-video-player) so future installs get the latest compatible. Do not pin to an exact version unless you have verified it exists on npm."cloudinary-video-player": "^1.0.0" - ✅ Package names only: Use only these names: ,
@cloudinary/react,@cloudinary/url-gen(standalone player),cloudinary-video-player(Node server-side only). Do not invent names (e.g. nocloudinary).@cloudinary/video-player - ❌ WRONG: or
npm install cloudinary-video-player@1.2.3(exact pin) — versions may not exist and break installs."cloudinary-video-player": "1.2.3" - ✅ Correct: (no version) or in package.json:
npm install cloudinary-video-player(caret = latest compatible)."cloudinary-video-player": "^1.0.0"
- ✅ 安装最新版本:添加Cloudinary依赖时,使用不带版本号,让npm安装最新的兼容版本(例如
npm install <package>)。package.json中使用插入号范围(例如npm install cloudinary-video-player),这样后续安装会获取最新兼容版本。除非你确认某个版本确实在npm上存在,否则不要固定到精确版本。"cloudinary-video-player": "^1.0.0" - ✅ 仅使用官方包名:仅使用以下包名:、
@cloudinary/react、@cloudinary/url-gen(独立播放器)、cloudinary-video-player(仅Node服务端使用)。不要自创包名(例如不要用cloudinary)。@cloudinary/video-player - ❌ 错误用法:或
npm install cloudinary-video-player@1.2.3(固定精确版本)—— 版本可能不存在,导致安装失败。"cloudinary-video-player": "1.2.3" - ✅ 正确用法:(不带版本号)或package.json中写
npm install cloudinary-video-player(插入号 = 最新兼容版本)。"cloudinary-video-player": "^1.0.0"
Import Patterns
导入模式
- ✅ Import Cloudinary instance:
import { cld } from './cloudinary/config' - ✅ Import components:
import { AdvancedImage, AdvancedVideo } from '@cloudinary/react' - ✅ Import plugins:
import { responsive, lazyload, placeholder } from '@cloudinary/react' - ✅ For transformations and overlays, use only the exact paths in "Import reference: @cloudinary/url-gen" and the "Canonical overlay block" below. Do not guess subpaths (e.g. and
textare fromimage, notqualifiers/source).actions/overlay
- ✅ 导入Cloudinary实例:
import { cld } from './cloudinary/config' - ✅ 导入组件:
import { AdvancedImage, AdvancedVideo } from '@cloudinary/react' - ✅ 导入插件:
import { responsive, lazyload, placeholder } from '@cloudinary/react' - ✅ 转换和叠加层相关导入,仅使用「@cloudinary/url-gen导入对照表」和下文「标准叠加层代码块」中的精确路径。不要猜测子路径(例如和
text从image导入,而非qualifiers/source)。actions/overlay
Import reference: @cloudinary/url-gen (use these exact paths only)
导入对照表:@cloudinary/url-gen(仅使用以下精确路径)
Rule: Do not invent or guess import paths for . Use only the paths in the table and canonical block below. Copy the import statements exactly; do not derive paths (e.g. exports only — and are from ; is from , not ). Wrong paths cause "module not found" or "does not exist".
@cloudinary/url-gen@cloudinary/url-gen/overlaysourcetextimagequalifiers/sourcePositionqualifiers/positionpositioning/Position| Purpose | Exact import |
|---|---|
| Cloudinary instance (config) | |
| Resize (fill) | |
| Resize (scale, for overlays) | |
| Delivery format/quality | |
| Format qualifier (auto) | |
| Quality qualifier (auto) | |
| Effects (e.g. blur) | |
| Overlay source | |
| Overlay text / image (source types) | |
| Overlay image transformation | |
| Position (overlay) | |
| Gravity/compass | |
| Text style (overlay) | |
| Types | |
Canonical overlay block (copy these imports and patterns exactly):
ts
// Overlay imports — text/image from qualifiers/source, NOT actions/overlay
import { source } from '@cloudinary/url-gen/actions/overlay';
import { text, image } from '@cloudinary/url-gen/qualifiers/source';
import { Position } from '@cloudinary/url-gen/qualifiers/position';
import { TextStyle } from '@cloudinary/url-gen/qualifiers/textStyle';
import { compass } from '@cloudinary/url-gen/qualifiers/gravity';
import { Transformation } from '@cloudinary/url-gen/transformation/Transformation';
import { scale } from '@cloudinary/url-gen/actions/resize';
// Text overlay (compass with underscores: 'south_east', 'center')
cld.image('id').overlay(
source(text('Hello', new TextStyle('Arial', 60).fontWeight('bold')).textColor('white'))
.position(new Position().gravity(compass('center')))
);
// Image overlay (logo/image with resize)
cld.image('id').overlay(
source(image('logo').transformation(new Transformation().resize(scale().width(100))))
.position(new Position().gravity(compass('south_east')).offsetX(20).offsetY(20))
);- Components (AdvancedImage, AdvancedVideo, plugins) come from , not from
@cloudinary/react.@cloudinary/url-gen - Transformation actions and qualifiers (resize, delivery, effect, overlay, etc.) come from and
@cloudinary/url-gen/actions/*with the exact subpaths above.@cloudinary/url-gen/qualifiers/* - If an import fails, verify the package version (in package.json) and the Cloudinary URL-Gen SDK docs or Transformation Builder reference.
@cloudinary/url-gen
规则:不要自创或猜测的导入路径,仅使用下表和标准代码块中的路径,严格复制导入语句,不要推导路径(例如仅导出 —— 和来自**;来自**,而非)。错误的路径会导致「模块未找到」或「不存在」错误。
@cloudinary/url-gen@cloudinary/url-gen/overlaysourcetextimagequalifiers/sourcePositionqualifiers/positionpositioning/Position| 用途 | 精确导入语句 |
|---|---|
| Cloudinary实例(配置) | |
| 调整大小(fill) | |
| 调整大小(scale,用于叠加层) | |
| 交付格式/质量 | |
| 格式限定符(auto) | |
| 质量限定符(auto) | |
| 效果(例如模糊) | |
| 叠加层源 | |
| 叠加层文本/图片(源类型) | |
| 叠加层图片转换 | |
| 位置(叠加层) | |
| 重力/方位 | |
| 文本样式(叠加层) | |
| 类型 | |
标准叠加层代码块(严格复制以下导入和模式):
ts
// 叠加层导入 —— text/image来自qualifiers/source,不是actions/overlay
import { source } from '@cloudinary/url-gen/actions/overlay';
import { text, image } from '@cloudinary/url-gen/qualifiers/source';
import { Position } from '@cloudinary/url-gen/qualifiers/position';
import { TextStyle } from '@cloudinary/url-gen/qualifiers/textStyle';
import { compass } from '@cloudinary/url-gen/qualifiers/gravity';
import { Transformation } from '@cloudinary/url-gen/transformation/Transformation';
import { scale } from '@cloudinary/url-gen/actions/resize';
// 文本叠加层(compass参数用下划线:'south_east', 'center')
cld.image('id').overlay(
source(text('Hello', new TextStyle('Arial', 60).fontWeight('bold')).textColor('white'))
.position(new Position().gravity(compass('center')))
);
// 图片叠加层(logo/图片带resize)
cld.image('id').overlay(
source(image('logo').transformation(new Transformation().resize(scale().width(100))))
.position(new Position().gravity(compass('south_east')).offsetX(20).offsetY(20))
);- 组件(AdvancedImage、AdvancedVideo、插件)来自****,不是
@cloudinary/react。@cloudinary/url-gen - 转换动作和限定符(resize、delivery、effect、overlay等)来自**和
@cloudinary/url-gen/actions/***,严格使用上述子路径。@cloudinary/url-gen/qualifiers/* - 如果导入失败,请验证package.json中的版本,参考Cloudinary URL-Gen SDK文档或转换构建器参考。
@cloudinary/url-gen
Creating Image & Video Instances
创建图片和视频实例
- ✅ Create image instance:
const img = cld.image(publicId) - ✅ Create video instance: (same pattern as images)
const video = cld.video(publicId) - ✅ Public ID format: Use forward slashes for folders (e.g., )
'folder/subfolder/image' - ✅ Public IDs are case-sensitive and should not include file extensions
- ✅ Sample assets: Cloudinary may provide sample assets under . Assume they might not exist (users can delete them); always handle load errors and provide fallbacks (see Image gallery). When they exist, use them for examples and demos instead of requiring uploads first.
samples/ - ✅ Sample public IDs that may be available (use for galleries, demos; handle onError if missing):
- Images: ,
samples/cloudinary-icon,samples/two-ladies,samples/food/spices,samples/landscapes/beach-boat,samples/bike,samples/landscapes/girl-urban-view,samples/animals/reindeersamples/food/pot-mussels - Video:
samples/elephants
- Images:
- ✅ Default / most reliable: Start with for a single image; use the list above for galleries or variety. Prefer uploaded assets when the user has them.
samples/cloudinary-icon - ✅ Examples:
tsx
const displayImage = cld.image('samples/cloudinary-icon'); const displayVideo = cld.video('samples/elephants'); // Gallery: e.g. ['samples/bike', 'samples/landscapes/beach-boat', 'samples/food/spices', ...]
- ✅ 创建图片实例:
const img = cld.image(publicId) - ✅ 创建视频实例:(和图片模式一致)
const video = cld.video(publicId) - ✅ Public ID格式:文件夹用正斜杠分隔(例如)
'folder/subfolder/image' - ✅ Public ID区分大小写,不要包含文件扩展名
- ✅ 示例资源:Cloudinary可能在路径下提供示例资源,假设这些资源可能不存在(用户可以删除),请始终处理加载错误并提供 fallback(见图片画廊章节)。如果资源存在,可以用于示例和演示,不需要用户先上传。
samples/ - ✅ 可用的示例Public ID(用于画廊、演示;如果不存在请处理onError):
- 图片:、
samples/cloudinary-icon、samples/two-ladies、samples/food/spices、samples/landscapes/beach-boat、samples/bike、samples/landscapes/girl-urban-view、samples/animals/reindeersamples/food/pot-mussels - 视频:
samples/elephants
- 图片:
- ✅ 默认/最可靠的示例:单张图片优先用;画廊或需要多种资源时用上述列表。如果用户有自己上传的资源,优先使用上传的资源。
samples/cloudinary-icon - ✅ 示例:
tsx
const displayImage = cld.image('samples/cloudinary-icon'); const displayVideo = cld.video('samples/elephants'); // 画廊:例如 ['samples/bike', 'samples/landscapes/beach-boat', 'samples/food/spices', ...]
Transformation Patterns
转换模式
Image Transformations
图片转换
- ✅ Chain transformations on image instance:
tsx
const img = cld.image('id') .resize(fill().width(800).height(600)) .effect(blur(800)) .delivery(format(auto())) .delivery(quality(autoQuality())); - ✅ Pass to component:
<AdvancedImage cldImg={img} />
- ✅ 在图片实例上链式调用转换方法:
tsx
const img = cld.image('id') .resize(fill().width(800).height(600)) .effect(blur(800)) .delivery(format(auto())) .delivery(quality(autoQuality())); - ✅ 传入组件:
<AdvancedImage cldImg={img} />
Video Transformations
视频转换
- ✅ Chain transformations on video instance (same pattern as images):
tsx
const video = cld.video('id') .resize(fill().width(800).height(600)) .delivery(format(auto())); - ✅ Pass to component:
<AdvancedVideo cldVid={video} /> - ✅ Video transformations work the same way as image transformations
- ✅ 在视频实例上链式调用转换方法(和图片模式一致):
tsx
const video = cld.video('id') .resize(fill().width(800).height(600)) .delivery(format(auto())); - ✅ 传入组件:
<AdvancedVideo cldVid={video} /> - ✅ 视频转换和图片转换的用法完全一致
Transformation Best Practices
转换最佳实践
- ✅ Format and quality must use separate calls
.delivery() - ✅ Always end with auto format/quality: unless user specifies a particular format or quality
.delivery(format(auto())).delivery(quality(autoQuality())) - ✅ Use unless user specifies a focal point
gravity(auto()) - ✅ Same transformation syntax works for both images and videos
- ✅ 格式和质量必须使用独立的调用
.delivery() - ✅ 除非用户指定特定格式或质量,否则转换末尾始终添加自动格式/质量:
.delivery(format(auto())).delivery(quality(autoQuality())) - ✅ 除非用户指定焦点,否则使用
gravity(auto()) - ✅ 图片和视频使用相同的转换语法
Plugin Patterns
插件模式
- ✅ When the user asks for lazy loading or responsive images: Use the Cloudinary plugins from —
@cloudinary/react,responsive(),lazyload()— withplaceholder(). Do not use only nativeAdvancedImageor CSS-only responsive; the Cloudinary plugins handle breakpoints, lazy loading, and placeholders for Cloudinary URLs.loading="lazy" - ✅ Import plugins from
@cloudinary/react - ✅ Pass plugins as array:
plugins={[responsive(), lazyload(), placeholder()]} - ✅ Recommended plugin order:
- - First (handles breakpoints)
responsive() - - Second (shows placeholder while loading)
placeholder() - - Third (delays loading until in viewport)
lazyload() - - Last (if needed)
accessibility()
- ✅ Always add and
widthattributes to prevent layout shiftheight - ✅ Example:
tsx
<AdvancedImage cldImg={img} plugins={[responsive(), placeholder({ mode: 'blur' }), lazyload()]} width={800} height={600} />
- ✅ 当用户需要懒加载或响应式图片时:使用提供的Cloudinary插件 ——
@cloudinary/react、responsive()、lazyload()搭配placeholder()使用。不要仅用原生AdvancedImage或纯CSS实现响应式,Cloudinary插件会针对Cloudinary URL处理断点、懒加载和占位符。loading="lazy" - ✅ 从导入插件
@cloudinary/react - ✅ 以数组形式传入插件:
plugins={[responsive(), lazyload(), placeholder()]} - ✅ 推荐的插件顺序:
- - 第一个(处理断点)
responsive() - - 第二个(加载时显示占位符)
placeholder() - - 第三个(进入视口才加载)
lazyload() - - 最后(如果需要)
accessibility()
- ✅ 始终添加和
width属性避免布局偏移height - ✅ 示例:
tsx
<AdvancedImage cldImg={img} plugins={[responsive(), placeholder({ mode: 'blur' }), lazyload()]} width={800} height={600} />
Responsive Images Pattern
响应式图片模式
- ✅ Responsive images: Use the Cloudinary plugin with
responsive()resize (not only CSS). Lazy loading: Use the Cloudinaryfill()plugin withlazyload()(not onlyAdvancedImage).loading="lazy" - ✅ Use plugin with
responsive()resizefill() - ✅ Combine with and
placeholder()pluginslazyload() - ✅ Example:
tsx
const img = cld.image('id').resize(fill().width(800)); <AdvancedImage cldImg={img} plugins={[responsive(), placeholder({ mode: 'blur' }), lazyload()]} width={800} height={600} />
- ✅ 响应式图片:使用Cloudinary 插件搭配
responsive()调整大小(不要仅用CSS)。懒加载:使用Cloudinaryfill()插件搭配lazyload()(不要仅用AdvancedImage)。loading="lazy" - ✅ 插件搭配
responsive()调整大小使用fill() - ✅ 结合和
placeholder()插件使用lazyload() - ✅ 示例:
tsx
const img = cld.image('id').resize(fill().width(800)); <AdvancedImage cldImg={img} plugins={[responsive(), placeholder({ mode: 'blur' }), lazyload()]} width={800} height={600} />
Image gallery with lazy loading and responsive
带懒加载和响应式的图片画廊
- ✅ When the user asks for an image gallery with lazy loading and responsive: Use Cloudinary plugins with :
AdvancedImage,responsive(),lazyload()(see Plugin Patterns). Useplaceholder()resize with the responsive plugin. Addfill()andwidthto prevent layout shift.height - ✅ Sample assets in galleries: Use the sample public IDs from "Creating Image & Video Instances" (e.g. ,
samples/bike,samples/landscapes/beach-boat,samples/food/spices,samples/two-ladies,samples/landscapes/girl-urban-view,samples/animals/reindeer,samples/food/pot-mussels). Assume any sample might not exist — users can delete them. Start with one reliable sample (e.g.samples/cloudinary-icon) or a short list; add onError handling and remove/hide failed images. Prefer uploaded assets when available (e.g. from UploadWidget) over samples.samples/cloudinary-icon - ✅ Handle load errors: Use on
onErrorto hide or remove failed images (e.g. set state to filter out the publicId, or hide the parent). Provide user feedback (e.g. "Some images could not be loaded. Try uploading your own!") and upload functionality so users can add their own images.AdvancedImage - ✅ Fallback: Default gallery list can be a subset of the sample list (e.g. ); when user uploads, append
['samples/cloudinary-icon', 'samples/bike', 'samples/landscapes/beach-boat']. If an image fails to load, remove it from the list or hide it so the UI doesn't show broken images.result.public_id
- ✅ 当用户需要带懒加载和响应式的图片画廊时:搭配使用Cloudinary插件:
AdvancedImage、responsive()、lazyload()(见插件模式)。placeholder()调整大小搭配响应式插件使用。添加fill()和width避免布局偏移。height - ✅ 画廊中的示例资源:使用「创建图片和视频实例」中的示例Public ID(例如、
samples/bike、samples/landscapes/beach-boat、samples/food/spices、samples/two-ladies、samples/landscapes/girl-urban-view、samples/animals/reindeer、samples/food/pot-mussels)。假设任何示例都可能不存在——用户可以删除这些资源。从一个可靠的示例(例如samples/cloudinary-icon)或短列表开始;添加onError处理,移除/隐藏加载失败的图片。优先使用用户上传的资源(例如来自UploadWidget的资源)而非示例资源。samples/cloudinary-icon - ✅ 处理加载错误:在上使用
AdvancedImage隐藏或移除加载失败的图片(例如设置state过滤掉publicId,或隐藏父元素)。给用户反馈(例如「部分图片加载失败,你可以尝试上传自己的图片!」)并提供上传功能,让用户可以添加自己的图片。onError - ✅ 降级方案:默认画廊列表可以是示例列表的子集(例如);用户上传后将
['samples/cloudinary-icon', 'samples/bike', 'samples/landscapes/beach-boat']追加到列表中。如果图片加载失败,从列表中移除或隐藏,避免UI显示损坏的图片。result.public_id
Image Overlays (text or logos)
图片叠加层(文本或logo)
- ✅ When the user asks for image overlays with text or logos: Use overlay APIs. Copy imports and patterns from the "Import reference" table and "Canonical overlay block" in these rules. Do not import
@cloudinary/url-genortextfromimage— they are fromactions/overlay; onlyqualifiers/sourceis fromsource.actions/overlay - ✅ Import from
source;actions/overlayandtextfromimage. Also:qualifiers/sourcefromPosition,qualifiers/positionfromTextStyle,qualifiers/textStylefromcompass,qualifiers/gravityfromTransformation,transformation/Transformationfromscale.actions/resize - ✅ compass() takes string values, with underscores: ,
compass('center'),compass('south_east'). ❌ WRONG:compass('north_west')orcompass(southEast)(no camelCase).'southEast' - ✅ Overlay image: Use inside
new Transformation():.transformation(). ❌ WRONG:image('logo').transformation(new Transformation().resize(scale().width(100)))(image('logo').transformation().resize(...)does not return a chainable object)..transformation() - ✅ Text overlay: goes on TextStyle:
fontWeight.new TextStyle('Arial', 60).fontWeight('bold')goes on the text source (chained aftertextColor):text(...).text('Hello', new TextStyle('Arial', 60)).textColor('white') - ✅ Position is chained after , not inside:
source(...).source(image('logo').transformation(...)).position(new Position().gravity(compass('south_east')).offsetX(20).offsetY(20)) - ✅ Image overlay pattern: . (Import
baseImage.overlay(source(image('id').transformation(new Transformation().resize(scale().width(100)))).position(new Position().gravity(compass('south_east')).offsetX(20).offsetY(20)))fromscaleif needed.)@cloudinary/url-gen/actions/resize - ✅ Text overlay pattern: .
baseImage.overlay(source(text('Your Text', new TextStyle('Arial', 60).fontWeight('bold')).textColor('white')).position(new Position().gravity(compass('center')))) - ✅ Docs: React Image Transformations and transformation reference for overlay syntax.
- ✅ 当用户需要添加文本或logo图片叠加层时:使用的叠加层API。严格复制本规则中「导入对照表」和「标准叠加层代码块」的导入和模式。不要从
@cloudinary/url-gen导入actions/overlay或text——它们来自**image**;仅qualifiers/source来自source。actions/overlay - ✅ 导入从
source导入;**actions/overlay和text从image**导入。同时导入:qualifiers/source从Position,qualifiers/position从TextStyle,qualifiers/textStyle从compass,qualifiers/gravity从Transformation,transformation/Transformation从scale。actions/resize - ✅ compass() 接收字符串参数,用下划线分隔:、
compass('center')、compass('south_east')。❌ 错误用法:compass('north_west')或compass(southEast)(不要用驼峰命名)。'southEast' - ✅ 叠加层图片:在内使用
.transformation():new Transformation()。❌ 错误用法:image('logo').transformation(new Transformation().resize(scale().width(100)))(image('logo').transformation().resize(...)不返回可链式调用的对象)。.transformation() - ✅ 文本叠加层:设置在TextStyle上:
fontWeight。new TextStyle('Arial', 60).fontWeight('bold')设置在文本源上(在textColor后链式调用):text(...)。text('Hello', new TextStyle('Arial', 60)).textColor('white') - ✅ Position 链式调用在**之后**,不是内部:
source(...)。source(image('logo').transformation(...)).position(new Position().gravity(compass('south_east')).offsetX(20).offsetY(20)) - ✅ 图片叠加层模式:。(如果需要从
baseImage.overlay(source(image('id').transformation(new Transformation().resize(scale().width(100)))).position(new Position().gravity(compass('south_east')).offsetX(20).offsetY(20)))导入@cloudinary/url-gen/actions/resize。)scale - ✅ 文本叠加层模式:。
baseImage.overlay(source(text('Your Text', new TextStyle('Arial', 60).fontWeight('bold')).textColor('white')).position(new Position().gravity(compass('center')))) - ✅ 文档:React图片转换和转换参考中的叠加层语法。
Upload Widget Pattern
上传组件模式
- ✅ Use component:
import { UploadWidget } from './cloudinary/UploadWidget'
Strict initialization pattern (always follow this exactly):
- ✅ Script in (required):
index.html
html
<script src="https://upload-widget.cloudinary.com/global/all.js" async></script>- ✅ Poll in useEffect until is available (required): Use
createUploadWidget(e.g. every 100ms) to checksetInterval. Only create the widget when this returnstypeof window.cloudinary?.createUploadWidget === 'function'. Clear the interval once ready.true - ✅ Add a timeout (e.g. 10 seconds) to stop polling and show an error state if the script never loads. Clear both interval and timeout in cleanup and when ready.
- ✅ Create widget once, store in a ref. Cleanup: clear interval, clear timeout, remove click listener.
❌ Do NOT: Check only (the function may not be attached yet); do a single check in (unreliable timing); skip and rely only on dynamic injection; poll forever without a timeout.
window.cloudinaryonloadindex.html- ✅ Create unsigned upload preset in dashboard at
settings/upload/presets - ✅ Add to :
.envVITE_CLOUDINARY_UPLOAD_PRESET=your_preset_name - ✅ Handle callbacks:
tsx
<UploadWidget onUploadSuccess={(result) => { console.log('Public ID:', result.public_id); }} onUploadError={(error) => { console.error('Upload failed:', error); }} /> - ✅ Upload result contains: ,
public_id,secure_url,width, etc.height
For complete Upload Widget configuration options (all properties for ), see the official reference: https://cloudinary.com/documentation/upload_widget_reference.md
createUploadWidget- ✅ 使用组件:
import { UploadWidget } from './cloudinary/UploadWidget'
严格初始化模式(始终遵循):
- ✅ 在中引入脚本(必填):
index.html
html
<script src="https://upload-widget.cloudinary.com/global/all.js" async></script>- ✅ 在useEffect中轮询直到可用(必填):使用
createUploadWidget(例如每100ms)检测setInterval,仅当返回typeof window.cloudinary?.createUploadWidget === 'function'时才创建组件,准备就绪后清除定时器。true - ✅ 添加超时逻辑(例如10秒),如果脚本始终未加载完成则停止轮询并展示错误状态。在清理函数和准备就绪时同时清除定时器和超时器。
- ✅ 仅创建一次组件,存入ref中。清理逻辑:清除定时器、清除超时器、移除点击监听。
❌ 禁止操作:仅检测(函数可能还未挂载);仅在中做单次检测(时机不可靠);不在中引入脚本仅依赖动态注入;无超时无限轮询。
window.cloudinaryonloadindex.html- ✅ 在控制台的路径下创建未签名上传预设
settings/upload/presets - ✅ 添加到:
.envVITE_CLOUDINARY_UPLOAD_PRESET=your_preset_name - ✅ 处理回调:
tsx
<UploadWidget onUploadSuccess={(result) => { console.log('Public ID:', result.public_id); }} onUploadError={(error) => { console.error('Upload failed:', error); }} /> - ✅ 上传结果包含:、
public_id、secure_url、width等字段。height
如需完整的上传组件配置选项(的所有属性),查看官方参考:https://cloudinary.com/documentation/upload_widget_reference.md
createUploadWidgetSigned vs unsigned uploads (when to use which)
签名vs未签名上传(适用场景)
Unsigned uploads (simpler, no backend required):
- Use when: Quick prototypes, low-risk apps, or when anyone with the preset name may upload.
- Preset: Create an Unsigned upload preset in Cloudinary dashboard (Settings → Upload → Upload presets). Put preset name in as
.env.VITE_CLOUDINARY_UPLOAD_PRESET - Client: Widget needs only and
cloudName. No API key or secret; no backend.uploadPreset - Trade-off: Anyone who knows the preset name can upload. Use only when that is acceptable.
Signed uploads (more secure, backend required):
- Use when: Production apps, authenticated users, or when you need to control who can upload.
- Preset: Create a Signed upload preset in the dashboard. The backend generates a signature using your API secret; the client never sees the secret.
- Client: Widget gets (from your backend),
api_key, and anuploadPresetfunction that calls your backend for each upload. API secret stays on server only.uploadSignature - Trade-off: Requires a backend (Node/Express, Next.js API route, etc.) to sign requests. More secure; signature validates each upload.
Rule of thumb: Default to unsigned uploads unless the user explicitly asks for "secure" or "signed" uploads. Do not default to signed — it requires a running backend and will fail out of the box. Use signed only when the user explicitly requests secure/signed uploads or needs to restrict who can upload.
未签名上传(更简单,不需要后端):
- 适用场景:快速原型、低风险应用,或者允许任何知道预设名称的用户上传的场景。
- 预设:在Cloudinary控制台(设置 → 上传 → 上传预设)中创建未签名上传预设,将预设名称存入的
.env字段。VITE_CLOUDINARY_UPLOAD_PRESET - 客户端:组件仅需要和
cloudName,不需要API密钥或secret,不需要后端。uploadPreset - 权衡:任何知道预设名称的人都可以上传,仅在可接受该风险时使用。
签名上传(更安全,需要后端):
- 适用场景:生产应用、需要认证的用户,或者需要控制上传权限的场景。
- 预设:在控制台创建签名上传预设。后端使用你的API secret生成签名,客户端永远不会获取到secret。
- 客户端:组件从你的后端获取、
api_key,以及uploadPreset函数(每次上传时调用后端获取签名)。API secret仅保存在服务端。uploadSignature - 权衡:需要后端(Node/Express、Next.js API路由等)对请求签名,安全性更高,签名会校验每次上传的合法性。
经验法则:默认使用未签名上传,除非用户明确要求「安全」或「签名」上传。不要默认使用签名上传——它需要运行中的后端,开箱即会失败。仅当用户明确要求安全/签名上传或需要限制上传权限时才使用签名上传。
Secure (Signed) Uploads
安全(签名)上传
When to use: Production apps, authenticated users, or when you need to control who can upload (more secure than unsigned).
Golden rules:
- Never expose or commit the API secret (server-only)
- Use in
server/.envfor API key/secret.gitignore - API key can be sent to client; API secret must stay server-only
Quick implementation:
- Use as function (not
uploadSignature)signatureEndpoint - Fetch from server before creating widget
api_key - Include in widget config
uploadPreset - Server includes in signed params
upload_preset - Use Cloudinary Node.js SDK v2 on server
For complete implementation patterns, client/server code examples, and troubleshooting, see references/signed-uploads.md
适用场景:生产应用、认证用户,或者需要控制上传权限的场景(比未签名更安全)。
黄金规则:
- 永远不要暴露或提交API secret(仅服务端使用)
- 将服务端的加入
.env,存储API密钥和secret.gitignore - API key可以发送到客户端;API secret必须仅保存在服务端
快速实现:
- 作为函数传入(不要用
uploadSignature)signatureEndpoint - 创建组件前从服务端获取
api_key - 组件配置中包含
uploadPreset - 服务端在签名参数中包含
upload_preset - 服务端使用Cloudinary Node.js SDK v2版本
完整实现模式、客户端/服务端代码示例和问题排查,查看 references/signed-uploads.md
Video Patterns
视频模式
- ✅ Display a video → Use AdvancedVideo (). It just displays a video (with optional transformations). Not a full player.
@cloudinary/react - ✅ A video player → Use Cloudinary Video Player (). That is the actual player (styled UI, controls, playlists, etc.).
cloudinary-video-player
- ✅ 展示视频 → 使用AdvancedVideo(),仅用于展示视频(可搭配转换),不是完整的播放器。
@cloudinary/react - ✅ 视频播放器 → 使用Cloudinary Video Player(),是完整的播放器(带样式UI、控制栏、播放列表等)。
cloudinary-video-player
⚠️ IMPORTANT: Two Different Approaches
⚠️ 重要:两种不同的方案
1. AdvancedVideo () — For displaying a video
@cloudinary/react- React component similar to ; just displays a video with Cloudinary transformations
AdvancedImage - Not a full "player" — it's video display (native HTML5 video with optional controls)
- Use when: user wants to show/display a video. Works with like images with
cld.video()cld.image()
2. Cloudinary Video Player () — The player
cloudinary-video-player- Full-featured video player (styled UI, controls, playlists). Use when the user asks for a "video player."
- Use imperative video element only (create with document.createElement, append to container ref); do not pass a React-managed . See "Cloudinary Video Player (The Player)" below.
<video ref>
1. AdvancedVideo()—— 用于展示视频
@cloudinary/react- 和类似的React组件,仅用于展示带Cloudinary转换的视频
AdvancedImage - 不是完整的「播放器」—— 仅做视频展示(原生HTML5 video,可选带控制栏)
- 适用场景:用户仅需要展示/显示视频,和用法一样,搭配
cld.image()使用cld.video()
2. Cloudinary Video Player()—— 完整播放器
cloudinary-video-player- 全功能视频播放器(带样式UI、控制栏、播放列表),用户明确要求「视频播放器」时使用。
- 仅使用命令式创建video元素(用document.createElement创建,追加到容器ref);不要传入React管理的,见下文「Cloudinary视频播放器」章节。
<video ref>
AdvancedVideo (React SDK - For Displaying a Video)
AdvancedVideo(React SDK - 用于展示视频)
- ✅ Purpose: Display a video with Cloudinary transformations (resize, effects, etc.). It is not a full player — it is for showing a video. For a player, use Cloudinary Video Player.
- ✅ Package: (same as AdvancedImage)
@cloudinary/react - ✅ Import:
import { AdvancedVideo } from '@cloudinary/react' - ✅ NO CSS IMPORT NEEDED: AdvancedVideo uses native HTML5 video - no CSS import required
- ❌ WRONG: (this path doesn't exist)
import '@cloudinary/react/dist/cld-video-player.css' - ✅ Create video instance: (like
const video = cld.video(publicId))cld.image() - ✅ Apply transformations: Chain transformations like images:
tsx
const video = cld.video('video-id') .resize(fill().width(800).height(600)) .delivery(format(auto())); - ✅ Use component:
tsx
<AdvancedVideo cldVid={video} controls autoplay muted /> - ✅ Documentation: https://cloudinary.com/documentation/react_video_transformations.md
- ✅ 用途:展示带Cloudinary转换(调整大小、效果等)的视频,不是完整播放器,仅用于展示视频。需要播放器请使用Cloudinary Video Player。
- ✅ 包:(和AdvancedImage同包)
@cloudinary/react - ✅ 导入:
import { AdvancedVideo } from '@cloudinary/react' - ✅ 不需要导入CSS:AdvancedVideo使用原生HTML5 video,不需要导入CSS
- ❌ 错误用法:(该路径不存在)
import '@cloudinary/react/dist/cld-video-player.css' - ✅ 创建视频实例:(和
const video = cld.video(publicId)用法一致)cld.image() - ✅ 应用转换:和图片一样链式调用转换方法:
tsx
const video = cld.video('video-id') .resize(fill().width(800).height(600)) .delivery(format(auto())); - ✅ 组件用法:
tsx
<AdvancedVideo cldVid={video} controls autoplay muted /> - ✅ 文档:https://cloudinary.com/documentation/react_video_transformations.md
Cloudinary Video Player (The Player)
Cloudinary 视频播放器(完整播放器)
Use when the user asks for a video player (styled UI, controls, playlists). For just displaying a video, use AdvancedVideo instead.
Critical rule: Imperative element only
- ❌ Do NOT pass React-managed (causes removeChild errors)
<video ref> - ✅ Use , append to container ref, pass to
document.createElement('video')videoPlayer(el, ...)
Quick setup:
- Package:
npm install cloudinary-video-player - Import: and CSS
import { videoPlayer } from 'cloudinary-video-player' - Source: (object, not string)
player.source({ publicId }) - Cleanup: then
player.dispose()if (el.parentNode) el.parentNode.removeChild(el) - Always include
posterOptions: { transformation: { startOffset: '0' }, posterColor: '#0f0f0f' }
For complete implementation pattern, cleanup, error handling, and troubleshooting, see references/video-player.md
用户明确要求视频播放器(带样式UI、控制栏、播放列表)时使用。仅需要展示视频请用AdvancedVideo。
核心规则:仅使用命令式元素
- ❌ 不要传入React管理的(会导致removeChild错误)
<video ref> - ✅ 使用,追加到容器ref,传入
document.createElement('video')videoPlayer(el, ...)
快速初始化:
- 安装包:
npm install cloudinary-video-player - 导入:和对应的CSS
import { videoPlayer } from 'cloudinary-video-player' - 设置源:(传入对象,不是字符串)
player.source({ publicId }) - 清理:然后
player.dispose()if (el.parentNode) el.parentNode.removeChild(el) - 始终添加
posterOptions: { transformation: { startOffset: '0' }, posterColor: '#0f0f0f' }
完整实现模式、清理逻辑、错误处理和问题排查,查看 references/video-player.md
When to Use Which?
适用场景对比
- ✅ Use AdvancedVideo when: User wants to display or show a video (no full player). It just displays a video with transformations.
- ✅ Use Cloudinary Video Player when: User asks for a video player — the actual player with styled UI, controls, and optional features (playlists, ads, etc.).
- ✅ 使用AdvancedVideo:用户仅需要展示或显示视频(不需要完整播放器),仅展示带转换的视频。
- ✅ 使用Cloudinary Video Player:用户明确要求视频播放器—— 带样式UI、控制栏和可选功能(播放列表、广告等)的完整播放器。
TypeScript Patterns
TypeScript模式
Essential TypeScript usage:
- Type imports:
import type { CloudinaryImage, CloudinaryVideo } from '@cloudinary/url-gen' - Upload results: Define interface
CloudinaryUploadResult - Environment variables: Create with
vite-env.d.tsinterfaceImportMetaEnv - Avoid : Use proper interfaces or
anywith type guardsunknown - Type refs: ,
useRef<HTMLVideoElement>(null)for widgetsuseRef<unknown>(null)
For complete TypeScript patterns, type guards, ref typing, and error solutions, see references/typescript-patterns.md
核心TypeScript用法:
- 类型导入:
import type { CloudinaryImage, CloudinaryVideo } from '@cloudinary/url-gen' - 上传结果:定义接口
CloudinaryUploadResult - 环境变量:创建,定义
vite-env.d.ts接口ImportMetaEnv - 避免:使用合适的接口或带类型守卫的
anyunknown - ref类型:组件用,部件用
useRef<HTMLVideoElement>(null)useRef<unknown>(null)
完整TypeScript模式、类型守卫、ref类型定义和错误解决方案,查看 references/typescript-patterns.md
Best Practices
最佳实践
- ✅ Always use resize with automatic gravity for responsive images
fill() - ✅ Always end transformations with unless the user specifies a format or quality
.delivery(format(auto())).delivery(quality(autoQuality())) - ✅ Use and
placeholder()plugins togetherlazyload() - ✅ Always add and
widthattributes toheightAdvancedImage - ✅ Store from upload success, not full URL
public_id - ✅ Video player: use imperative element only; dispose in useLayoutEffect cleanup and remove element with ; always include
if (el.parentNode) el.parentNode.removeChild(el)withposterOptionsandtransformation: { startOffset: '0' }for reliable poster displayposterColor: '#0f0f0f' - ✅ Use TypeScript for better autocomplete and error catching
- ✅ Prefer over
unknownwhen types aren't availableany - ✅ Use type guards for runtime type checking
- ✅ Define interfaces for Cloudinary API responses
- ✅ Create for environment variable typing
vite-env.d.ts - ✅ Use proper HTML element types for refs
- ✅ 响应式图片始终使用调整大小搭配自动重力
fill() - ✅ 除非用户指定格式或质量,转换末尾始终添加
.delivery(format(auto())).delivery(quality(autoQuality())) - ✅ 搭配使用和
placeholder()插件lazyload() - ✅ 始终给添加
AdvancedImage和width属性height - ✅ 上传成功后存储,不要存储完整URL
public_id - ✅ 视频播放器:仅使用命令式元素;在useLayoutEffect清理函数中dispose并使用移除元素;始终包含
if (el.parentNode) el.parentNode.removeChild(el),设置posterOptions和transformation: { startOffset: '0' }确保封面可靠展示posterColor: '#0f0f0f' - ✅ 使用TypeScript获得更好的自动补全和错误捕获
- ✅ 类型未知时优先使用而非
unknownany - ✅ 使用类型守卫做运行时类型检查
- ✅ 为Cloudinary API响应定义接口
- ✅ 创建为环境变量提供类型
vite-env.d.ts - ✅ 为ref使用正确的HTML元素类型
⚠️ COMMON ERRORS & SOLUTIONS
⚠️ 常见错误与解决方案
For detailed error solutions and troubleshooting, see references/troubleshooting.md
详细的错误解决方案和问题排查,查看 references/troubleshooting.md
Quick Error Reference
快速错误参考
Environment Variable Errors
环境变量错误
- Env vars: Wrong prefix, missing VITE_, not restarted → Use correct bundler prefix, restart, clear cache
- Imports: Wrong package/path → Use exact paths from Import reference table
- Upload Widget: "createUploadWidget is not a function" → Poll with setInterval, don't check only
window.cloudinary - Transformations: Not working → Chain properly, use v2 syntax, separate format/quality
- Video Player: removeChild errors → Use imperative element (createElement), not React ref
- TypeScript: Type errors → See references/typescript-patterns.md
- Signed uploads: Invalid signature → See references/signed-uploads.md
- 环境变量:前缀错误、缺失VITE_、未重启服务 → 使用正确的打包工具前缀、重启服务、清除缓存
- 导入错误:包/路径错误 → 使用导入对照表中的精确路径
- 上传组件:"createUploadWidget is not a function" → 使用setInterval轮询,不要仅检测
window.cloudinary - 转换:不生效 → 正确链式调用、使用v2语法、分开设置格式/质量
- 视频播放器:removeChild错误 → 使用命令式元素(createElement),不要用React ref
- TypeScript:类型错误 → 查看 references/typescript-patterns.md
- 签名上传:签名无效 → 查看 references/signed-uploads.md
Most Common Issues
最高频问题
- Environment variables undefined: Clear , restart dev server, hard refresh browser
node_modules/.vite/ - "createUploadWidget is not a function": Poll with until
setIntervaltypeof window.cloudinary?.createUploadWidget === 'function' - Wrong imports: Use ONLY paths from Import reference table - don't guess subpaths
- Upload fails: Check preset exists, is Unsigned (for unsigned), dev server restarted
- Video player errors: Use imperative element only, include posterOptions
- Overlay issues: Import /
textfromimage, notqualifiers/sourceactions/overlay
For complete troubleshooting with detailed solutions, see references/troubleshooting.md
- 环境变量未定义:清除、重启开发服务、强制刷新浏览器
node_modules/.vite/ - "createUploadWidget is not a function":用轮询直到
setIntervaltypeof window.cloudinary?.createUploadWidget === 'function' - 导入错误:仅使用导入对照表中的路径——不要猜测子路径
- 上传失败:检查预设是否存在、是否为未签名模式(未签名上传场景)、开发服务是否重启
- 视频播放器错误:仅使用命令式元素、包含posterOptions
- 叠加层问题:从导入
qualifiers/source/text,不要从image导入actions/overlay
完整的问题排查和详细解决方案,查看 references/troubleshooting.md