首页 > 解决方案 > 如何将 Assets 文件夹中的压缩文件复制到 DocumentDirectoryPath?

问题描述

在一个 react-native 项目中,我有一个 android_assets 文件夹中的压缩文件。我想解压缩此文件夹并将其复制到 DocumentDirectoryPath。我已经导入了 react-native-zip-archive 并使用了 unzipAssets,但它似乎不起作用。我使用了以下代码,但出现错误:“./ICF-Package”无法打开。

const assetsPath = './ICF-Package.zip' const targetPath =${DocumentDirectoryPath}/ICF-Package.zip

  copyfile() {
      unzipAssets(assetPath, targetPath)
         .then(() => {
           console.log('unzip completed!')
           })
           .catch((error) => {
             console.log(error)
           })
    }

标签: react-nativeandroid-assets

解决方案


您可以安装它并尝试解决问题。

  1. $ npm install react-native-fetch-blob
  2. $ react-native link react-native-fetch-blob
import RNFetchBlob from 'react-native-fetch-blob';
import { unzip } from 'react-native-zip-archive';

let dirs = RNFetchBlob.fs.dirs
const documentPath = dirs.DocumentDir
const resourceUrl = 'file:///android_asset/target.zip'

    downloadResource = () => {

        // Set the path to store on the device
        const dirs = RNFetchBlob.fs.dirs.DocumentDir
        const homePath = dirs + '/target.zip'

        RNFetchBlob
            .config({
                path: homePath
            })
            .fetch('GET', resourceUrl)
            .progress((received, total) => {
                const percentage = Math.floor(received / total * 10000) / 100 + '%'
                console.log(percentage)
            })
            .then(resourceFile => {
                console.log('target.zip file download success')

                this.unzip(resourceFile);
            })
            .catch((errorMessage, statusCode) => {
                console.log(errorMessage);
            })
    }


    unzip = resourceFile => {
        const resourcePath = resourceFile.path()
        unzip(resourcePath, documentPath)
            .then(path => {
                console.log(`unzip sucess: ${path}`)
            })
    }


推荐阅读