node.js - 如何使用 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[]'.
任何想法为什么会发生这种情况?
解决方案
我使用以下代码解决了这个问题:
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
})
推荐阅读
- kubernetes - 将 helm hooks 添加到 RBAC 资源
- javascript - 我将如何编写一个函数来返回等于目标总和 WITH RECURSION 的 3 个数字的所有组合
- google-app-engine - 如何通过 app.yaml 将环境变量传递给谷歌应用引擎?
- java - 如何在Java中找到列表的偶数
- r - 你怎么说`[`和`[[`?
- java - 如何创建具有相同超类的多个类型的列表,而不会丢失类型
- javascript - 如何将 Cropper.js 与已经上传到我的服务器的图像一起使用,而不是裁剪然后将图像上传到正确的文件夹
- javascript - 为什么我在 discord.js 中使用此 Slash 命令时收到错误“无效的交互应用程序命令”?
- haskell - 如何获取 Haskell 代码字符串(连同值)
- java - flink-connector-redis 中如何设置 TTL 使 Redis 的 key 过期?