首页 > 解决方案 > 如何使用 multer 和 typescript 正确处理节点发布请求中的 req.files

问题描述

我正在使用multer并有一个文件req.files,其中req.files来自在我的端点中使用以下中间件版本:

..., upload.array('file', 1)...

我已经定义了一个multer文件接口如下:

interface multerFile {
    buffer: Buffer, 
    encoding: string, 
    fieldname: string, 
    mimetype: string, 
    originalname: string, 
    size: number;
};

然后我想我可以创建一个类似文件的数组,并按req.files如下方式分配给它:

let files: multerFile[] = [];
files = req.files;

然后我想将我拥有的一个文件推送到一组附件中:

attachments.push({
    "type": files[0].mimetype,
    "name": files[0].originalname,
    "content": files[0].buffer
})

但是,这不起作用,因为我收到此错误:

error TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type '{ [fieldname: string]: File[]; } | File[]'.

我还安装了multer类型,并认为我可以执行以下操作:

    const request: Express.Request = req;
    const files: Express.Multer.File[] = request.files;

但是,这仍然给我一个错误。

error TS2322: Type 'File[] | { [fieldname: string]: File[]; }' is not assignable to type 'File[]'.

任何想法为什么会发生这种情况?

标签: node.jstypescriptmultipartform-datamulter

解决方案


我使用以下代码解决了这个问题:

req.body.thumbnails = req.files
const {enName , fullName , type , price , desc , category , instrument , thumbnails } = req.body

await new ProductModel().createProduct({
  enName , fullName , type , price , desc , category , instrument , sellCount , thumbnails 
})

推荐阅读