使用Express Node Typescript上传Multer文件

时间:2018-06-30 20:40:27

标签: node.js typescript express file-upload multer

我正在努力使此文件上载正常工作。以下是相关的代码段。

我已经将其与普通JS和标准节点服务器一起使用,但这有所不同。

doOnSuccess

}

const storage = multer.diskStorage({
destination: (req, file, callback) => {
    callback(null, path.resolve('./../assets/Uploads/Data'));
},
filename: (req, file, callback) => {
    var name = file.originalname.split('.')[0] + '-' + Date.now() + path.extname(file.originalname);
    name = _.replace(name, /\s/g, '_');
    callback(null, name);
},})

const upload = multer({ storage: storage });

xport class Routes {
public fileUploadController: FileUploadController = new FileUploadController();

public routes(app: any): void {
    try {
        app.route('/').get((req: Request, res: Response) => {
            try {
                console.log(chalk.cyanBright('Request from: ') + chalk.yellowBright(req.originalUrl));
                console.log(chalk.cyanBright('Request type: ') + chalk.yellowBright(req.method));

                res.status(200).send({
                    statusCode: 200,
                    message: 'What reason do you have for wanting to access the root route ?-_-?',
                });
            } catch (error) {
                console.error(chalk.redBright(error));
            }
        });

        // NOT SURE WHERE TO PUT THE FOLLOWING LINE OF CODE: --> upload.single('file') <--
        app.route('/upload').post((req: Request, res: Response, next: NextFunction) => {
            try {
                console.log(chalk.cyanBright('Request from: ') + chalk.yellowBright(req.originalUrl));
                console.log(chalk.cyanBright('Request type: ') + chalk.yellowBright(req.method));

                next();
            } catch (error) {
                console.error(chalk.redBright(error));
            }
        }, this.fileUploadController.upload);
    } catch (error) {
        console.error(chalk.redBright(error));
    }
}

0 个答案:

没有答案