首页 > 解决方案 > 如何从节点服务器获取 zip 文件到 react-native 客户端

问题描述

我试图将一个 zip 文件从节点服务器发送到 react-native 客户端。在服务器中,我使用“adm-zip”并将缓冲区发送到客户端。我找不到在客户端中保存和解压缩文件的方法。

这是我在节点服务器中的代码:

const zip = new AdmZip();
for (let i = 0; i < files.length; i++) {
     zip.addLocalFile(files[i].path);
}
const downloadName = `zipFiles.zip`;
const data = zip.toBuffer();
// save file zip in root directory
        
zip.writeZip(`${baseUrl.filesBaseUrl}${req.params.screenId}/${req.params.userId}/${downloadName}`);

// code to download zip file
res.set('Content-Type','application/octet-stream');
res.set('Content-Disposition',`attachment; filename=${downloadName}`);
res.set('Content-Length',data.length);
res.send(data);

谢谢 :)

标签: node.jsreact-nativezipbufferunzip

解决方案


您可以使用 react-native lib react-native-fetch-blob

import RNFetchBlob from 'react-native-fetch-blob';
...
RNFetchBlob.config({
fileCache : true,
path: path + '/filename'})
.fetch('GET','URL ')
.progress((chunks, total) => {console.log('process', chunks / total)})
.then((res) => {
        console.log('The file saved to ', res.path());
});

要解压缩,您可以使用react-native-zip-archive

import { zip, unzip, unzipAssets, subscribe } from 'react-native-zip-archive'

const targetPath = `${DocumentDirectoryPath}/myFile.zip`
const sourcePath = DocumentDirectoryPath

zip(sourcePath, targetPath)
.then((path) => {
  console.log(`zip completed at ${path}`)
})
.catch((error) => {
  console.error(error)
})

有关更多详细信息,请查看此处


推荐阅读