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

Sharp无法读取express-fileupload文件缓冲区报错解决

问题描述

在Node.js服务中使用express-fileupload中间件读取API接口上传的文件时,希望直接通过Sharp库处理请求体中的图片,无需先将文件保存到服务器后再调用fs.readFileSync读取处理。

最初尝试传入req.files.image.data(预期为Buffer类型)作为Sharp的入参,实现代码如下:

const image = await sharp(Buffer.from(req.files.image.data))
  .resize(500, 500)
  .jpeg({ quality: 10 })
  .toBuffer()
  .then((outputBuffer) =>
    ({ data: outputBuffer, mimetype: 'image/jpeg' }))
  .catch(err => {
    console.log(err);
    return null;
  });

运行代码后抛出错误:
[Error: VipsJpeg: Premature end of input file]

后续尝试先将图片缓冲区数据转为字符串,再通过Buffer.from转回缓冲区传入Sharp,又抛出错误:
[Error: Input buffer contains unsupported image format]

根因分析

以上报错是因为express-fileupload默认配置的文件大小上限为5MB,超过该限制的图片无法被完整捕获到缓冲区中,传入Sharp的是截断的不完整文件数据,因此触发解析错误。

解决方法

调整express-fileupload的文件大小上限配置到符合业务需求的数值即可,例如设置上限为50MB,配置代码如下:

app.use(fileUpload({
  limits: { fileSize: 50 * 1024 * 1024 },
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:57:20