我正在使用 multer
并且在 req.files
中有一个文件,其中 req.files
来自使用以下 middleware我的端点中的版本:..., upload.array('file', 1)...
我定义了一个 multer
文件界面如下:
interface multerFile {
buffer: Buffer,
encoding: string,
fieldname: string,
mimetype: string,
originalname: string,
size: number;
};
然后我想我可以创建一个类似文件的 multer 数组,并分配
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[]'.
任何想法为什么会发生这种情况?
最佳答案
我使用以下代码修复了这个问题:
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
})
关于node.js - 如何使用multer和 typescript 正确处理 Node 发布请求中的req.files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57631753/