将ZIP文件解压缩后再将其内容保存到multer中

3

我有一个类似于Express的REST API,并且通过Multer启用了文件上传功能。

我的文件上传相关逻辑全部在Multer中处理,我希望保持这种方式。 最近有一个新的文件类型要添加到这个端点(.zip),但我并不想保存它。我希望能够重复使用已经实现的Multer逻辑,但在传递文件给Multer之前加入一个先决步骤,以便它可以像往常一样保存它们并完成流程。

目前我所拥有的:

routes.post(
  '/upload',
  multer(multerConfig).single('file'),
  async (req, res) => {
    const { path: filePath } = req.file

    const file = xlsx.readFile(filePath)
    const cells = Object.values(file.Sheets).reduce((accumulator, sheet) => {
      const sheetCellsKeys = Object.keys(sheet)

      const sortedCellsKeys = sheetCellsKeys
        .sort((previousCell, currentCell) => (
          previousCell.localeCompare(currentCell, 'en', { numeric: true })
        ))

      const validCellsKeys = sortedCellsKeys.filter((cellKey) => (
        /^[A-Z]+[0-9]+$/.test(cellKey)
      ))

      const grouppedCellsKeys = groupBy(validCellsKeys, (cellKey) => (
        cellKey.replace(/\D/g, '')
      ))

      return [
        ...accumulator,
        ...Object.values(grouppedCellsKeys)
          .reduce((cellsAccumulator, cellsKeys) => ([
            ...cellsAccumulator,
            cellsKeys.map((cellKey) => (
              sheet[cellKey].v
            )),
          ]), []),
      ]
    }, [])

    res.send(cells)
  },
)

我想解压我的zip文件,并将其传递给multer,就像它的内容被发送到/process端点一样。这是否可能?

1个回答

1
我不知道如何更新 multer 的值。但在这种情况下,我将创建一个中间件函数,并将其设置在 multer 中间件之后,在此中间件中,我将提取 zip 文件,并将 zip 文件的内容保存到存储文件夹中,最后,通过 req.file 对象将新文件路径传递给下一个流程(因为在最后一个流程中,您只需要 Excel 文件的路径)。
以下代码仅是我的想法示例:
新的中间件
const unzipMiddleware = (req, res, next) => {
  const { path: zipFilePath, mimetype } = req.file // zipFilePath is './public/uploads/file.zip'
  if (mimetype !== 'application/gzip') { // You would want to check that, I think so
    return next() // do nothing
  }
  // get content of the zipFilePath [1.xlsx, 2.xlsx, 3.xlsx,....]
  // extract the zip file to storage path (maybe the same with multer setting - ./public/uploads/)

  // update the value of the file info
  req.file = {
    path: './public/uploads/3.xlsx' // example, you just use the last file
  }

  next() // continue, important line
}

使用新中间件

routes.post(
  '/upload',
  multer(multerConfig).single('file'),
  unzipMiddleware, // use new middleware here, after multer middleware
  async (req, res) => {
    const { path: filePath } = req.file // now filePath will be './public/uploads/3.xlsx', instead of './public/uploads/file.zip'
    //... your logic
  }
)

1
我一开始也是这么想的,但我在想如何“修改”我的请求,以便 multer 中间件只接收未压缩的文件,也许如果我的 unzipMiddleware 在 multer 之前使用,那么会怎样呢?我是否可以安全地操作我的请求,以便将已经过处理的数据传递给 multer? - rnarcos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接