代码之家  ›  专栏  ›  技术社区  ›  phoebus

nodejs-multer-根据请求属性更改文件名

  •  0
  • phoebus  · 技术社区  · 8 年前

    我知道可以通过如下存储对象用multer更改文件名:

    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, process.env.UPLOAD_DIR);
        },
        filename: (req, file, cb) => {
            cb(null, 'bla.png');
        }
    });
    const upload = multer({ storage: storage } );
    

    我的请求除了包含文件外,还包含一些文本属性,如 name: myPic.png .

    是否可以根据其他请求属性或在控制器内动态更改文件名,如下所示:

    filename: (req, file, cb) => {
         cb(null, `${req.body.name}.png`);
    }
    

    或

    router.post('/upload', upload.single('pic'), myController.upload);
    
    /* in controller */
    upload = async (req: Request, res: Response) => {
        try {
    
            /* change the filename of multer here? */
    
        } catch (err) {
            winston.error(`Error while uploading: ${err.message}`);
            winston.error(`Stack trace: ${err.stack}`);
            sendJSONResponse(res, err, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Vasan    8 年前

    multer是两个填充 req.body 并存储文件。

    而且,当它到达 filename() 函数,不能保证文本字段将填充在 正文 因为这取决于客户的订单 sends them in (见最后一条注释)。

    据我所见,你有两个选择:

    1)在multer upload中间件完成其任务并填充后重命名上载的文件 正文 以及 req.file . 所以在你的控制器上传中间件中,你可以做如下事情:

    if (req.file) {
        fs.renameSync(req.file.path, req.file.destination + req.body.name);
    }
    

    2)将请求正文文本字段更改为查询参数。然后,在里面 文件类型() 你可以做 req.query.name .

    顾客:这不是一个很安静的设计,但也许对你来说不是那么重要。