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

如何将C# MemoryStream的zip内容转为字符串传递给JS实现下载

问题根因

你当前的核心错误就是用ASCII编码直接转换二进制Zip流为字符串:ASCII是单字节7位编码,所有字节值大于127的二进制数据都会被转义/丢弃,直接破坏了Zip文件的二进制结构。你能看到文件列表是因为Zip的文件目录头信息刚好都是ASCII范围内的字符,所以能正常解析,但实际的文件内容已经被编码损坏。

修复方案

C#后端修改

不要用Encoding.ASCII.GetString处理二进制流,改为将字节数组转换为Base64字符串传输,二进制数据不会丢失:

// 替换原错误代码
// lCallBackResult.HtmlCode = Encoding.ASCII.GetString(lMemoryStream.ToArray());
lCallBackResult.HtmlCode = Convert.ToBase64String(lMemoryStream.ToArray());

前端JS修改

首先修正Zip的MIME类型为标准的application/zip,拿到Base64字符串后先转成二进制Uint8数组再生成Blob:

// 调用处修改MIME类型
DOWFileWND(lFileName, 'application/zip', pCallbackResult.htmlcode);

function DOWFileWND (pFileName, pFileType, pBase64Content)  {
    // Base64转二进制数组
    const binaryStr = window.atob(pBase64Content);
    const bytes = new Uint8Array(binaryStr.length);
    for (let i = 0; i < binaryStr.length; i++) {
        bytes[i] = binaryStr.charCodeAt(i);
    }

    const lData = new Blob([bytes], { type: pFileType });

    // 原有下载逻辑保持不变
    if (window.navigator && window.navigator.msSaveOrOpenBlob) 
    { 
        window.navigator.msSaveOrOpenBlob(lData, pFileName);
    } 
    else 
    { 
        const lLink = document.createElement("a");
        document.body.appendChild(lLink);
        lLink.style = "display: none";

        const lUrl = URL.createObjectURL(lData);
        lLink.href =  lUrl;
        lLink.download = pFileName;
        lLink.click();
        URL.revokeObjectURL(lLink.href);
        lLink.remove();
    }
};

内容的提问来源于stack exchange,提问作者Fabio Alves Francelino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:06:06