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

在React中获取public文件夹图片并转换为File类型的实现方法

ReadableStream转File实现方案

fetch请求返回的响应体默认是ReadableStream格式,你可以通过浏览器原生的Response.blob()方法先将流转换为Blob对象,再传入File构造函数生成符合要求的File实例,具体实现如下:

基础实现代码

// 异步方法获取public目录图片并转为File
const fetchPublicImageToFile = async (publicImgPath, targetFileName, mimeType = 'image/jpeg') => {
  // 发起请求获取图片资源
  const res = await fetch(publicImgPath);
  // 自动读取ReadableStream并转为Blob对象
  const imgBlob = await res.blob();
  // 构造File实例
  return new File([imgBlob], targetFileName, { type: mimeType });
}

// 调用示例:获取public目录下的demo.jpg
const run = async () => {
  const imgFile = await fetchPublicImageToFile('/demo.jpg', 'demo.jpg', 'image/jpeg');
  // 此处imgFile可直接传入要求File类型参数的API
  console.log(imgFile instanceof File); // 输出true
}

优化版(自动获取MIME类型)

无需手动指定图片格式,直接从响应头读取Content-Type:

const fetchPublicImageToFile = async (publicImgPath, targetFileName) => {
  const res = await fetch(publicImgPath);
  const imgBlob = await res.blob();
  const mimeType = res.headers.get('content-type') || 'image/jpeg';
  return new File([imgBlob], targetFileName, { type: mimeType });
}

原理解释

Response.blob()是浏览器原生封装的流处理方法,会自动消费整个ReadableStream,将所有数据块拼接为完整的Blob对象,无需开发者手动监听流事件处理数据拼接,兼容所有支持Fetch API的现代浏览器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 05:15:02