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

React Native 0.71.2中Blob转URL失败及字节数组获取问题求助

解决React Native 0.71.2中Blob获取及URL创建失败问题

问题根源

React Native的Blob实现和Web标准存在差异,URL.createObjectURL并非RN原生支持的API;且axios返回的response.data是RN封装的Blob对象(即你看到的带blobId的结构),无法直接用Web端的方式处理。

可行解决方案

方案1:借助react-native-fs保存本地(推荐用于视频播放场景)

通过react-native-fs库将Blob写入本地文件,再获取本地文件URL:

  1. 安装依赖:
npm install react-native-fs --save
# 或使用yarn
yarn add react-native-fs
  1. 修改请求代码:
import RNFS from 'react-native-fs';

// ... 其余代码逻辑
await axios({
    method: "POST",
    url: forumServerIP + 'api',
    data: jsonData,
    responseType: 'blob',
})
.then(async (response) => {
    const rnBlob = response.data;
    // 指定本地存储路径
    const localFilePath = RNFS.DocumentDirectoryPath + '/temp-video.mp4';
    
    // 将Blob写入本地文件
    await RNFS.writeFile(localFilePath, rnBlob, 'base64');
    
    // 生成可用于播放的本地文件URL
    const fileUrl = `file://${localFilePath}`;
    console.log(fileUrl);
})
.catch(function (error) {
    console.log(error);
});

方案2:转换为Base64处理字节数据

若仅需获取字节数组或生成可直接使用的资源URI:

await axios({
    method: "POST",
    url: forumServerIP + 'api',
    data: jsonData,
    responseType: 'blob',
})
.then(async (response) => {
    const rnBlob = response.data;
    // 将RN Blob转换为Base64字符串
    const base64Str = await rnBlob.base64();
    
    // 从Base64转换为字节数组
    const byteArray = Uint8Array.from(atob(base64Str), char => char.charCodeAt(0));
    console.log(byteArray);
    
    // 生成data URI,可用于图片/视频展示
    const dataUrl = `data:video/mp4;base64,${base64Str}`;
    console.log(dataUrl);
})
.catch(function (error) {
    console.log(error);
});

方案3:改用fetch替代axios

RN原生fetch对Blob的处理更贴合平台特性:

fetch(forumServerIP + 'api', {
    method: 'POST',
    body: JSON.stringify(jsonData),
    headers: {
        'Content-Type': 'application/json',
    },
})
.then(response => response.blob())
.then(async (blob) => {
    // 后续可沿用上述转Base64或保存本地的逻辑
    const base64Str = await blob.base64();
    const dataUrl = `data:video/mp4;base64,${base64Str}`;
    console.log(dataUrl);
})
.catch(error => console.log(error));

关键注意事项

  • 不要在React Native中使用Web标准的URL.createObjectURL处理RN Blob
  • RN的Blob对象自带base64()方法,可直接转换为Base64格式
  • 视频播放场景优先使用本地file:// URL,性能优于data URI

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:17:31