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

如何使用Google App Script通过文件URL上传文件至Cloudinary

使用Google Apps Script通过URL将文件上传到Cloudinary

前置准备

  • 从Cloudinary控制台获取你的云名称(cloud name)、API密钥和API密钥(API secret)。
  • 确保要上传的文件URL是公开可访问的(Cloudinary需要能直接抓取该文件)。

完整实现脚本

function uploadFileFromUrlToCloudinary() {
  // 替换为你的Cloudinary凭证
  const cloudName = 'YOUR_CLOUD_NAME';
  const apiKey = 'YOUR_API_KEY';
  const apiSecret = 'YOUR_API_SECRET';
  
  // 要上传的目标文件URL
  const fileUrl = 'https://example.com/path/to/your/file.jpg';
  
  // 构建Cloudinary上传端点(根据文件类型调整,比如视频用/video/upload)
  const uploadUrl = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
  
  // 生成安全签名(生产环境必加,防止未授权上传)
  const timestamp = Math.floor(Date.now() / 1000);
  const signaturePayload = `timestamp=${timestamp}${apiSecret}`;
  const signature = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, signaturePayload)
    .map(byte => ('0' + (byte & 0xFF).toString(16)).slice(-2))
    .join('');
  
  // 上传请求参数
  const payload = {
    file: fileUrl,
    api_key: apiKey,
    timestamp: timestamp,
    signature: signature,
    // 可选:自定义文件名、添加标签等
    // public_id: 'my-custom-file-name',
    // tags: 'gapps-script,cloudinary-upload'
  };
  
  try {
    const requestOptions = {
      method: 'post',
      payload: payload,
      muteHttpExceptions: true // 开启后能捕获详细错误信息
    };
    
    const response = UrlFetchApp.fetch(uploadUrl, requestOptions);
    const responseData = JSON.parse(response.getContentText());
    
    if (response.getResponseCode() === 200) {
      console.log('上传成功!文件安全URL:', responseData.secure_url);
      // 可扩展:把URL写入Google Sheets、发送通知等
    } else {
      console.error('上传失败:', responseData.error.message);
    }
  } catch (err) {
    console.error('请求出错:', err.toString());
  }
}

关键说明

  1. 凭证替换:把代码中占位的凭证值换成你自己的Cloudinary账号信息,否则上传会失败。
  2. 文件类型适配:如果上传的是视频、音频或其他文件,需要修改uploadUrl中的资源类型部分:
    • 视频:/video/upload
    • 音频:/raw/upload
    • 其他文件:/raw/upload
  3. 签名机制:签名是Cloudinary的安全校验方式,生成时要确保timestamp和签名的计算逻辑正确,避免签名不匹配导致上传被拒绝。
  4. 权限授权:第一次运行脚本时,Google会提示授权UrlFetchApp的网络访问权限,必须允许才能正常发送请求。

注意事项

  • 如果目标文件URL需要登录或其他认证才能访问,Cloudinary无法直接抓取,这种情况需要先将文件下载到Google Drive,再从Drive上传到Cloudinary(但这不符合你要的URL上传方式,仅作补充说明)。
  • 可以根据需求添加更多Cloudinary上传参数,比如folder指定存储文件夹、quality调整文件质量等。

内容的提问来源于stack exchange,提问作者Nived Padikkal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:39:35