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

Node.js文件下载大小异常求助:特定格式文件下载后体积变大

Node.js文件下载体积异常问题解决

你的问题核心是用UTF-8编码读取二进制文件导致的:

  • 你通过fs.readFileSync(filePath, 'utf8')把所有文件都当成UTF-8文本读取,但iso、deb、sqlite这类属于二进制文件,UTF-8编码会错误解析非文本字节,既破坏了原始数据,又因为编码转换导致文件体积异常膨胀。
  • 而txt、html、jpg/png这类文件,要么本身就是UTF-8文本格式,要么二进制数据结构巧合适配UTF-8读取规则,所以下载表现正常。

修正后的代码

将文件读取逻辑改为二进制模式(直接读取Buffer,不指定编码):

const filePath = path.join(directoryPath, fileName);
if (fs.existsSync(filePath)) {
    const fileExtension = path.extname(fileName);
    let fileType = mime.contentType(fileExtension);
    const HEADER = { 
        'Content-Type': fileType, 
        'Content-Disposition': `attachment; filename="${fileName}"` 
    };
    // 直接读取二进制Buffer,无需指定编码
    const fileBuffer = fs.readFileSync(filePath);
    res.writeHead(200, HEADER);
    res.end(fileBuffer);
} else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end("File not found");
}

额外优化建议

  1. 大文件改用流式读取,避免占用过多内存:
// 替换readFileSync部分
const stream = fs.createReadStream(filePath);
res.writeHead(200, HEADER);
stream.pipe(res);
  1. 处理文件名中的特殊字符,避免浏览器解析异常:
'Content-Disposition': `attachment; filename="${encodeURIComponent(fileName)}"`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 16:30:44