React Native中使用JSZip生成zip并上传application/zip格式文件的方法
解决方案
问题根因
你之前使用binarystring或普通string作为JSZip输出格式时,字符串在HTTP传输过程中会发生编码转义,导致二进制结构被破坏,所以服务器收到的压缩包格式错误。React Native环境下优先选择base64作为JSZip的输出格式,既避免了blob不兼容问题,也能保证二进制数据的传输完整性。
适配RNFetchBlob的修改方案
第一步:调整JSZip生成配置
把原来的zip生成逻辑替换为输出base64格式:
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); } // 生成base64格式的压缩包,兼容React Native环境 const zipBase64 = await zip.generateAsync({ type: 'base64', compression: 'DEFLATE', compressionOptions: { level: 9 } }); const res = await PhotoService.uploadLogs(routeId, zipBase64); } catch (error) { console.log(error); } };
第二步:调整uploadLogs请求配置
RNFetchBlob支持直接识别带base64,前缀的内容作为二进制请求体,不需要额外转换:
uploadLogs(driverRouteId: number, zipBase64: string) { const store = getStore(); const token = store.getState()?.auth?.token || ''; return RNFetchBlob.fetch( 'POST', `${API_HOST}driver/route/${driverRouteId}/logs`, { 'Content-Type': 'application/zip', Authorization: `Bearer ${token}` }, // 加base64前缀,RNFetchBlob会自动转换为二进制流发送 `base64,${zipBase64}` ); }
适配axios的备选方案
如果你更习惯使用axios,可将base64格式的压缩包转为Uint8Array后直接上传:
// 新增base64转Uint8Array工具方法 const base64ToUint8Array = (base64: string) => { const binary = atob(base64); const len = binary.length; const bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }; // axios上传逻辑 const uploadLogsWithAxios = async (driverRouteId: number, zipBase64: string) => { const store = getStore(); const token = store.getState()?.auth?.token || ''; return axios.post( `${API_HOST}driver/route/${driverRouteId}/logs`, base64ToUint8Array(zipBase64), { headers: { 'Content-Type': 'application/zip', Authorization: `Bearer ${token}` } } ); };
内容的提问来源于stack exchange,提问作者Tzvetlin Velev
相关产品推荐
相关产品推荐

