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

如何通过编程将图片上传至Cloudflare R2?是否需使用WORKERS?

代码上传图片到Cloudflare的方案及Workers必要性说明

是否必须使用Workers?

不需要,Workers只是可选的中间层方案,Cloudflare提供了多种直接通过代码上传图片的方式,根据你的需求选择即可。

常用代码上传方式

1. 直接调用Cloudflare Images API上传

这是最直接的方式,适合单纯上传图片到Cloudflare Images服务的场景:

  • 先在Cloudflare控制台创建具有Cloudflare Images > Edit权限的API令牌;
  • 用HTTP POST请求上传,支持curl、各种语言的HTTP库调用:

curl示例:

curl -X POST "https://api.cloudflare.com/client/v4/accounts/{你的账户ID}/images/v1" \
  -H "Authorization: Bearer {你的API令牌}" \
  -F "file=@/本地图片路径/photo.jpg" \
  -F "metadata={\"key\":\"value\"}" # 可选,添加自定义元数据

Node.js fetch示例:

import fs from 'fs';
import fetch from 'node-fetch';

const accountId = '你的账户ID';
const apiToken = '你的API令牌';
const imagePath = './photo.jpg';

const formData = new FormData();
formData.append('file', fs.createReadStream(imagePath));
formData.append('metadata', JSON.stringify({name: '我的图片'}));

const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/images/v1`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiToken}`
  },
  body: formData
});

const result = await response.json();
console.log(result);

2. 上传到Cloudflare R2存储

如果需要自行管理存储(比如配合后续的图片处理、静态托管),可以用R2的S3兼容API上传:

  • 在Cloudflare控制台创建R2存储桶,生成API凭据(Access Key和Secret Key);
  • 使用S3兼容的SDK(比如AWS SDK)上传:

Node.js AWS SDK示例:

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import fs from 'fs';

const s3Client = new S3Client({
  region: 'auto',
  endpoint: 'https://{你的账户ID}.r2.cloudflarestorage.com',
  credentials: {
    accessKeyId: '你的R2 Access Key',
    secretAccessKey: '你的R2 Secret Key'
  }
});

const uploadParams = {
  Bucket: '你的存储桶名称',
  Key: 'photo.jpg', // 存储在R2中的文件名
  Body: fs.createReadStream('./photo.jpg')
};

const command = new PutObjectCommand(uploadParams);
await s3Client.send(command);

3. 用Workers作为中间层(可选)

如果需要额外的逻辑处理(比如用户权限验证、图片压缩、格式转换、生成预签名上传URL),可以用Workers做中转:

  • 示例场景:Workers接收前端上传的图片,先压缩再转发到Images/R2;
  • 核心逻辑示例(简化版):
export default {
  async fetch(request, env) {
    if (request.method !== 'POST') return new Response('Method not allowed', {status: 405});
    
    // 这里可以添加权限验证逻辑
    const formData = await request.formData();
    const file = formData.get('file');
    
    // 转发到Cloudflare Images API
    const uploadResponse = await fetch(`https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/images/v1`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${env.API_TOKEN}`
      },
      body: formData
    });
    
    return uploadResponse;
  }
};

总结

  • 简单上传需求:直接调用Images/R2的API即可,无需Workers;
  • 复杂业务逻辑:比如需要自定义验证、预处理,再考虑用Workers作为中间层。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:20:34