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

使用WebDAV上传ExcelJS生成的Excel文件失败求助

解决WebDAV上传Excel文件报‘Argument error, options.body’的问题

问题根源

你读取Excel文件时没有指定正确的编码方式:fs.readFile默认会把文件内容按UTF-8编码解析成字符串,而Excel是二进制格式,转成字符串后再转Buffer会损坏文件数据,导致WebDAV客户端处理请求体时抛出错误。文本文件本身是UTF-8编码,所以不受这个问题影响。

修复方案

修改文件读取逻辑,指定encoding: null让fs.readFile直接返回原始二进制Buffer,不需要额外转换:

修改后的异步读取代码

exports.saveToWebDAV = (file) => {
    const conOptions = {
        url: '', // 填入你的WebDAV服务地址
        authenticator: new webdav.DigestAuthenticator(),
        username: '', // 填入你的WebDAV用户名
        password: '', // 填入你的WebDAV密码
    }

    const connection = new webdav.Connection(conOptions);

    // 读取二进制文件时指定encoding: null,直接获取Buffer类型的文件内容
    fs.readFile(file, { encoding: null }, function (err, data) {
        if (err) throw err;
        // 直接传入原始Buffer,无需再转
        connection.put('/' + file, data, (error) => {
            if (error) throw error;
        });
    });
}

同步读取的修复代码

如果用readFileSync,同样需要指定encoding: null:

exports.saveToWebDAV = (file) => {
    const conOptions = {
        url: '',
        authenticator: new webdav.DigestAuthenticator(),
        username: '',
        password: '',
    }

    const connection = new webdav.Connection(conOptions);

    try {
        // 直接读取二进制Buffer
        const data = fs.readFileSync(file, { encoding: null });
        connection.put('/' + file, data, (error) => {
            if (error) throw error;
        });
    } catch (err) {
        throw err;
    }
}

额外检查项

  • 确认file参数是本地Excel文件的正确路径,没有拼写错误
  • 检查WebDAV目标路径'/' + file是否合法:如果file包含子目录,要确保WebDAV服务器上对应目录已存在(大部分WebDAV客户端不会自动创建目录)
  • 可以打印data.length,确认读取的文件大小和本地Excel文件一致,验证读取过程没有出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:42:26