如何使用 multer 和 typescript 正确处理节点发布请求中的 req.files

the*_*hme 10 multipartform-data node.js typescript multer

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

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

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

interface multerFile {
    buffer: Buffer, 
    encoding: string, 
    fieldname: string, 
    mimetype: string, 
    originalname: string, 
    size: number;
};
Run Code Online (Sandbox Code Playgroud)

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

let files: multerFile[] = [];
files = req.files;
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

    const request: Express.Request = req;
    const files: Express.Multer.File[] = request.files;
Run Code Online (Sandbox Code Playgroud)

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

error TS2322: Type 'File[] | { [fieldname: string]: File[]; }' is not assignable to type 'File[]'.
Run Code Online (Sandbox Code Playgroud)

有什么想法为什么会发生这种情况吗?

moh*_*iko 15

你需要修复类型。点击此链接

如果你正在使用

upload.array('photos', 12)
Run Code Online (Sandbox Code Playgroud)

在您的处理程序中尝试此代码

const files= req.files as Express.Multer.File[];
const myFirstfile=files[0];
Run Code Online (Sandbox Code Playgroud)

但如果你正在使用

upload.fields([{ name: 'avatar', maxCount: 1 }])
Run Code Online (Sandbox Code Playgroud)

试试这个

const files= req.files as  {[fieldname: string]: Express.Multer.File[]};
const myFirstAvatarFile=files['avatar'][0];
Run Code Online (Sandbox Code Playgroud)


Kry*_*ten 2

问题的出现似乎是因为req.files是因为它不是你想象的那样。

查看multer 文档,似乎类型req.files会根据您设置 multer 中间件的方式而有所不同。

文档的基本用法部分显示了三种不同的可能性:

var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})
Run Code Online (Sandbox Code Playgroud)

您尚未向我们展示您正在使用哪种形式的 multer 中间件,但您收到的错误表明您正在使用第三个选项而不是第二个选项。