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

Flask传输ZIP文件至NodeJS后端报错,寻求问题排查解决方法

问题分析与解决方案

核心问题

你的错误主要来自两个方面:Flask端的响应参数配置错误,以及NodeJS端未正确处理二进制响应数据。

Flask端代码修正

  1. 用with语句管理ZipFile,确保文件完全写入磁盘后再返回
  2. 修正send_file的参数(Flask官方函数为send_file而非sendfile),as_attachment需传布尔值而非字符串,同时使用标准的ZIP MIME类型
import zipfile
from flask import send_file

# 生成ZIP文件
with zipfile.ZipFile(filename, "w", compression=zipfile.ZIP_STORED) as zipfolder:
    zipfolder.write(file)
    zipfolder.write(file2)

# 返回ZIP文件
return send_file(
    filename,
    mimetype="application/zip",
    download_name=zfile,
    as_attachment=True
)

NodeJS端代码修正

关键要设置responseType: 'arraybuffer',让Axios以二进制格式接收响应,避免字符串转码损坏ZIP数据:

async function data(vars){
    try {
        const form = new FormData();
        // 在这里添加需要传递给Flask的表单数据,例如:
        // form.append('key', 'value');

        const resp = await axios.post(url, form, {
            headers: form.getHeaders(),
            maxBodyLength: Infinity,
            responseType: 'arraybuffer' // 必须配置,确保接收二进制数据
        });

        const zip = new JSZip();
        const z = await zip.loadAsync(resp.data);
        return z;
    } catch(err) {
        throw err;
    }
}

错误原因解释

  • HPE_INVALID_CONSTANT:原Flask代码中as_attachment="True"传递了字符串,导致HTTP响应头格式错误,触发NodeJS端的HTTP解析错误。
  • ZIP损坏/Base64错误:NodeJS端未配置responseType时,Axios默认将响应转为UTF-8字符串,二进制ZIP数据转码后丢失部分字节,无论是转Base64还是直接加载都会导致文件损坏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:04:42