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

如何在Cloudflare Workers中上传图片并转换为Base64?

在Cloudflare Workers中实现图片转Base64编码

Cloudflare Workers基于Web标准API运行,没有Node.js的fs、path等核心模块,因此需要通过Web原生API处理文件上传与编码。以下是满足你需求的完整实现方案:

完整代码实现

export default {
  async fetch(request, env, ctx) {
    // 响应GET请求,返回上传表单页面
    if (request.method === 'GET') {
      return new Response(`
        <html>
          <body>
            <form method="POST" enctype="multipart/form-data">
              <input type="file" name="image" accept="image/*" required>
              <button type="submit">上传并转换为Base64</button>
            </form>
          </body>
        </html>
      `, {
        headers: { 'Content-Type': 'text/html' }
      });
    }

    // 处理POST请求,完成图片转Base64逻辑
    if (request.method === 'POST') {
      try {
        // 解析表单数据
        const formData = await request.formData();
        const imageFile = formData.get('image');

        if (!imageFile || !(imageFile instanceof File)) {
          return new Response('请上传有效的图片文件', { status: 400 });
        }

        // 将文件转为ArrayBuffer
        const arrayBuffer = await imageFile.arrayBuffer();
        // 转换为Base64编码字符串
        const byteArray = new Uint8Array(arrayBuffer);
        const base64String = btoa(String.fromCharCode(...byteArray));
        // 拼接完整的Data URI
        const dataUri = `data:${imageFile.type};base64,${base64String}`;

        return new Response(`
          <html>
            <body>
              <h3>转换结果</h3>
              <textarea rows="12" cols="90" readonly>${dataUri}</textarea>
              <br><br>
              <h4>图片预览</h4>
              <img src="${dataUri}" alt="上传图片预览" style="max-width: 600px;">
            </body>
          </html>
        `, {
          headers: { 'Content-Type': 'text/html' }
        });
      } catch (error) {
        return new Response(`处理出错: ${error.message}`, { status: 500 });
      }
    }

    // 拒绝其他请求方法
    return new Response('仅支持GET/POST请求', { status: 405 });
  }
};

关键步骤说明

1. 文件上传处理

Workers通过Web标准的request.formData()方法解析POST表单数据,替代Node.js中读取本地文件的逻辑。你需要确保表单的enctype设置为multipart/form-data,才能正确传输文件。

2. 文件读取与Base64转换

  • 使用File.arrayBuffer()异步读取文件内容,这是Web环境中处理二进制文件的标准方式。
  • 将ArrayBuffer转为Uint8Array字节数组,再通过String.fromCharCode(...byteArray)转换为ASCII字符串,最后用原生的btoa()方法编码为Base64字符串。
  • 从imageFile.type自动获取图片的MIME类型,拼接成可直接使用的Data URI。

3. 环境差异注意点

  • Workers没有本地文件系统,无法像Node.js那样读取本地路径的文件,必须通过用户上传或从外部存储(如Cloudflare R2)获取文件内容。
  • btoa()仅支持ASCII字符串,通过字节数组转字符串的方式可确保二进制数据正确编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:52:40