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

React Native Expo应用图片下载解压后显示异常求助

修复React Native Expo中Zip解压后图片损坏的问题

问题根源

原代码中手动将Uint8Array分块转换为Base64的逻辑存在错误:

  • String.fromCharCode.apply(null, chunk)无法正确处理ASCII范围外的字节(比如图片中常见的大于127的字节),会导致字符编码失真,最终生成的Base64字符串错误,图片保存后出现部分灰色、损坏的情况。
  • 手动分块拼接Base64的操作冗余且容易出错,JSZip本身提供了更可靠的API直接获取Base64内容。

优化后的代码

直接使用JSZip内置的Base64获取方法,替代手动转换逻辑:

const readZipFile = async (uri: string, privateAssetsDirectory: string) => {
    try {
        const response = await axios.get(uri, { responseType: 'arraybuffer' });
        const zipBuffer = response.data;

        const zip = await JSZip.loadAsync(zipBuffer);
        const fileKeys = Object.keys(zip.files);

        for (const filename of fileKeys) {
            const file = zip.files[filename];
            if (!file.dir && !isSystemFile(filename)) {
                // 直接通过JSZip获取正确的Base64内容
                const base64Content = await file.async('base64');

                // 用模板字符串拼接路径,避免分隔符问题
                const filePath = `${privateAssetsDirectory}${filename}`;

                await FileSystem.writeAsStringAsync(
                    filePath,
                    base64Content,
                    { encoding: FileSystem.EncodingType.Base64 }
                );
            }
        }
    } catch (error) {
        console.error('读取Zip文件出错:', error);
        throw error;
    }
};

额外建议

  • 路径拼接优先使用模板字符串,避免因privateAssetsDirectory末尾缺少路径分隔符导致的文件路径错误。
  • 可以在保存后对比原Zip内文件的大小与本地保存文件的大小,确认数据完整性。
  • 若处理超大Zip文件,可考虑添加异步任务的进度监听,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:11:08