问题描述
我有一个类似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端点一样。有可能吗?
解决方法
我不知道如何更新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
}
)