如何在 react-native 中发送 `application/zip`

How to send `application/zip` in react-native

我想生成一个 zip 文件,然后 POST 将其上传。我正在尝试利用此库 JSZip 创建一个包含多个文件的 zip。这是我现在拥有的。

handlePendingItems = async (routeId: number) => {
    try {
      await dbClient.addLogLine(`Need to delete photos.`);
      const [debugLogs, pendingTasks, pendingUploads] = await this.getPendingItems();
      const dbVersion = await dbClient.getUserSchemaVersion();
      let appInfo = `Database Version = ${dbVersion}\n`;
      appInfo += `App Version = ${version}`;
      const zip = new JSZip();
      zip.file('app-info.txt', appInfo);
      if (debugLogs.length) {
        const debugLogsCsv = convertDataToCSV(debugLogs);
        zip.file('debug-logs.csv', debugLogsCsv);
      }
      if (pendingTasks.length) {
        const pendingTasksCsv = convertDataToCSV(pendingTasks);
        zip.file('pending-tasks.csv', pendingTasksCsv);
      }
      if (pendingUploads.length) {
        const pendingUploadsCsv = convertDataToCSV(pendingUploads);
        zip.file('pending-uploads.csv', pendingUploadsCsv);
      }
      const test = await zip.generateAsync({ type: 'binarystring' });
      console.log(test);
      const res = PhotoService.uploadLogs(routeId, test);

      // const zipFile = await zip.generateAsync({
      //   type: 'blob',
      //   compression: 'DEFLATE',
      //   compressionOptions: {
      //     level: 9
      //   }
      // });
    } catch (error) {
      console.log(error);
    }
  };

我不能在 react-native 中使用类型:'blob',它抛出一个错误,因为这个平台不受支持。话虽如此,我正在尝试使用其他类型传递给 react-native-fetch-blob。将通过以下代码发布。

  uploadLogs(driverRouteId: number, logs: string) {
    const store = getStore();
    const token = store.getState()?.auth?.token || '';

    return new Promise((resolve, reject) => {
      RNFetchBlob.fetch(
        'POST',
        `${API_HOST}driver/route/${driverRouteId}/logs`,
        {
          'Content-Type': 'application/zip',
          Authorization: `Bearer ${token}`
        },
        logs
      ).then(
        (res) => {
          console.log(res);
          resolve(res);
        },
        (err) => {
          console.log(err);
          debugger;
          reject(err);
        }
      );
    });
  }

我读到,如果内容编码是特定类型,则 fetch blob 将尝试解析 base64 字符串,在这种情况下必须是 application/zip(因此在这种情况下不进行解析)所以我正在尝试使用类型 string 调用 generateAsync 但是,服务器存储的文件的 zip 是 in an unsupported format。如何生成包含三个 csv 文件和 txt 文件的 zip 文件,并使用 fetch blob 或 react-native 中的普通 axios 发送它。

找到使用不同库进行压缩的解决方案。

npm install react-native-zip-archive --save
npm install react-native-fs --save
npm install rn-fetch-blob --save
import RNFetchBlob from 'rn-fetch-blob';
import { zip } from 'react-native-zip-archive';
import RNFS from 'react-native-fs';

const pathsToZip = [];
const zipPath = `${RNFS.DocumentDirectoryPath}/test.zip`;
const appInfo = 'App info string to put in txt file'
const appInfoPath = RNFS.DocumentDirectoryPath + '/appInfo.txt';
await RNFS.writeFile(appInfoPath, appInfo, 'utf8');
pathsToZip.push(appInfoPath);
await zip(pathsToZip, zipPath);

await uploadLogs(zipPath) {
    return new Promise((resolve, reject) => {
      RNFetchBlob.fetch(
        'POST',
        `postpath`,
        {
          'Content-Type': 'application/zip',
        },
        RNFetchBlob.wrap(zipPath)
      ).then(
        (res) => {
          console.log(res);
          resolve(res);
        },
        (err) => {
          console.log(err);
          debugger;
          reject(err);
        }
      );
    });
}