为什么我在使用 req.files.length 时收到打字稿错误?

问题描述 投票:0回答:1

我使用 multer 并想要访问 req.files,但我收到此打字稿错误:

Operator '<' cannot be applied to types 'number' and 'number | File[]'

使用 req.files.lenght 时会发生此错误;

app.post('/api/upload/images', [upload.array('image')], async (req: Request, res: Response) => {
  try {
    if(!req.files) {
      throw new ErrorException(500, 'Es ist ein Fehler beim Hochladen eines oder mehreren Bildern aufgetreten. Versuchen Sie es erneut.');
    }

    for(let i = 0; i < req.files.length; i++) {
      // Base 64 encode the file to create a data URI for the uploader
      const base64EncodedImage = Buffer.from(req.files[i].buffer).toString("base64")
      const dataUri = `data:${req.files[i].mimetype};base64,${base64EncodedImage}`
      
      // Use the cloudinary uploader to upload the image
      const response = await cloudinary.uploader.upload(dataUri, { folder: '/test2' });
      console.log(response);
    }
  return res.status(201).json({});
  } catch(e) {
    return res.status(500).json({err:'err'});
  }
});

如何修复该错误?我也只在 req.files 处收到错误。

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ [fieldname: string]: File[]; } | File[]'.
  No index signature with a parameter of type 'number' was found on type '{ [fieldname: string]: File[]; } | File[]'
node.js express multer
1个回答
0
投票

为什么我在使用 req.files.length 时收到打字稿错误?

因为

files
的类型是,如您所示,
{ [fieldname: string]: File[]; } | File[]

您可能会通过

multipart/form-data
上传,例如

<input type="file" name="image">
<input type="file" name="image">
<input type="file" name="image">

在这种情况下,

req.files
的形状将是

{"image": [File, File, File]}

由于您的代码始终需要一个数组,因此将

req.files
移至本地并添加类型保护 (
Array.isArray()
),其余部分将进行类型检查:

const files = req.files;
if (!(files && Array.isArray(files))) {
  throw new ErrorException(
    500,
    "Es ist ein Fehler beim Hochladen eines oder mehreren Bildern aufgetreten. Versuchen Sie es erneut.",
  );
}

for (let i = 0; i < files.length; i++) {
  // Base 64 encode the file to create a data URI for the uploader
  const base64EncodedImage = Buffer.from(files[i].buffer).toString("base64");
  const dataUri = `data:${files[i].mimetype};base64,${base64EncodedImage}`;

  // Use the cloudinary uploader to upload the image
  const response = await cloudinary.uploader.upload(dataUri, { folder: "/test2" });
  console.log(response);
}
© www.soinside.com 2019 - 2024. All rights reserved.