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

React中替换fs.createReadStream实现本地图片读取调用DALL-E接口

解决React中调用DALL-E图片变体时无法使用fs的问题

fs是Node.js专属的文件系统模块,仅能在服务器环境运行,React运行在浏览器端,没有这个API,所以无法直接用fs.createReadStream读取本地文件。下面提供两种可行的替换方案:

方案一:通过文件上传控件让用户选择本地图片

浏览器出于安全限制,不能直接访问本地文件系统,必须由用户主动选择文件。可以添加一个文件输入框,获取用户选择的图片后,将其转换为File对象传给OpenAI接口:

import { Configuration, OpenAIApi } from "openai";
import { useState } from "react";
import "./App.css";

function App() {
  const [selectedFile, setSelectedFile] = useState(null);

  const configuration = new Configuration({
    apiKey: import.meta.env.VITE_Open_AI_Key,
  });

  const openai = new OpenAIApi(configuration);

  const handleFileChange = (e) => {
    setSelectedFile(e.target.files[0]);
  };

  const generateImage = async () => {
    if (!selectedFile) {
      alert("请先选择图片");
      return;
    }

    try {
      const response = await openai.createImageVariation(
        selectedFile, // 直接传入File对象
        1,
        "1024x1024"
      );
      console.log(response.data.data[0].url);
    } catch (error) {
      console.error("生成图片失败:", error);
    }
  };

  return (
    <div>
      <input type="file" accept="image/png, image/jpeg" onChange={handleFileChange} />
      <button onClick={generateImage} disabled={!selectedFile}>generate an image</button>
    </div>
  );
}

export default App;

方案二:读取项目静态资源中的图片

如果图片放在React项目的public文件夹下(比如public/images/3.png),可以通过fetch获取图片资源并转换为Blob,再传给接口:

import { Configuration, OpenAIApi } from "openai";
import { useState } from "react";
import "./App.css";

function App() {
  const configuration = new Configuration({
    apiKey: import.meta.env.VITE_Open_AI_Key,
  });

  const openai = new OpenAIApi(configuration);

  const generateImage = async () => {
    try {
      // 从public文件夹获取图片
      const imageResponse = await fetch("/images/3.png");
      const blob = await imageResponse.blob();
      // 将Blob转换为File对象(指定文件名和类型)
      const file = new File([blob], "3.png", { type: blob.type });

      const response = await openai.createImageVariation(
        file,
        1,
        "1024x1024"
      );
      console.log(response.data.data[0].url);
    } catch (error) {
      console.error("生成图片失败:", error);
    }
  };

  return (
    <div>
      <button onClick={generateImage}>generate an image</button>
    </div>
  );
}

export default App;

注意事项

  • 确保你的OpenAI API Key有权限调用createImageVariation接口,且图片格式为PNG/JPEG,尺寸符合要求。
  • 原代码中console.log(res.data.data[0].url)存在变量名错误,应改为response.data.data[0].url,已在上述代码中修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:22:37