【问题标题】:How to move multer upload midddleware to another file如何将multer上传中间件移动到另一个文件
【发布时间】:2021-05-21 19:53:27
【问题描述】:

使用multergridFS 开发我正在开发的快速API。我无法将上传对象移动到另一个文件。我已经设置了multer 这样

export const upload = multer({
    storage,
});

以下代码在index.ts 中有效,其中multer 被启动,但在任何其他路由文件中无效。

router.post("/upload", single("image"), (req, res) => {
    const file = req.file;
    if (!file) {
        const error = new Error("Please upload a file");
        res.send(error);
    }
    res.send(file);
});

我不可能发布完整的 sn-p,但我希望这已经足够了。

干杯

【问题讨论】:

    标签: node.js express middleware multer


    【解决方案1】:

    我实际上可以通过添加以下内容来解决这个问题:

    app.use(
        multer({
            storage,
        }).single("image")
    );
    

    现在这可能意味着它将为每条路线运行,这是另一个需要解决的问题

    【讨论】:

      【解决方案2】:

      你可以这样做:

      所有路径

      app.use('*', multer({storage}).single("images"));
      

      仅用于发布请求

      app.post('*',multer({storage}).single("images"))
      

      适用于所有发布路线,但少数路线

      app.post('*',(req,res,next)=>{
        const exceptionPaths = ["singup","login"]//don't upload 
        if(exceptionPaths.includes(req.path))return next()
        next()
      },multer({storage}).single("images"))
      

      【讨论】:

        猜你喜欢
        • 2018-06-21
        • 2018-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        • 2013-08-25
        • 2012-07-13
        • 2013-04-27
        相关资源
        最近更新 更多