使用正文解析器传递 zip 文件

using body parser to pass zip file

我有使用 express 的节点应用程序,在我需要通过 post 消息 zip 文件 发送的应用程序中(例如从 postman 到节点服务器),目前我使用如下的正文解析器,但我想知道这是否可以?

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(bodyParser.text({
    type: 'application/text-enriched',
    limit: '10mb'
}));

顺便说一句,这是有效的,但我想知道我是否使用正确...

bodyParse.text() 适用于 string 类型的正文。来自文档:

bodyParser.text(options)

Returns middleware that parses all bodies as a string...

由于您正在上传二进制数据(例如 zip 文件),使用 bodyParser.text()convert your buffer body to utf-8 string。因此,您将丢失一些二进制文件的数据,并且 zip 文件可能无法读取。

对于二进制文件,使用 bodyParser.raw(),这将在 req.body 中为您提供一个缓冲区,您可以将该缓冲区安全地保存在文件中。

app.use(bodyParser.raw({
    type: 'application/octet-stream',
    limit: '10mb'
}));

对于文件上传,您真的应该看看 multer,它适用于 multipart/form-data 内容类型。