From 6d1bed7dacfb30b0aeb3f80e144bf9faa1040315 Mon Sep 17 00:00:00 2001 From: Yves Kaufmann <1507553+yveskaufmann@users.noreply.github.com> Date: Tue, 5 Nov 2019 22:21:16 +0100 Subject: [PATCH] [koa__multer] Allows to access the properties file and files through the koa context. (#40034) * [koa__multer] Allows to access the file nad files through the koa contet. * Extends the koa context and request by the fields file, files. * Removes unecessary import --- types/koa__multer/index.d.ts | 17 +++++++++++++++++ types/koa__multer/koa__multer-tests.ts | 6 ++++++ 2 files changed, 23 insertions(+) diff --git a/types/koa__multer/index.d.ts b/types/koa__multer/index.d.ts index b824b37181..b5f510e1a3 100644 --- a/types/koa__multer/index.d.ts +++ b/types/koa__multer/index.d.ts @@ -19,6 +19,11 @@ * async function uploadFile(ctx: Koa.Context){ * let multerReq = ctx.req; * let files = multerReq.files; + * + * // You can also directly access the files property from the context object or request object: + * files = ctx.files; + * files = ctx.request.files; + * * let baseFilePath: string = ctx.params.path || ''; * //... * } @@ -32,6 +37,18 @@ import * as Koa from 'koa'; import { IncomingMessage } from 'http'; +declare module 'koa' { + interface DefaultContext { + file: multer.File; + files: multer.File[]; + } + + interface Request { + file: multer.File; + files: multer.File[]; + } +} + declare namespace multer { interface File { /** Field name specified in the form */ diff --git a/types/koa__multer/koa__multer-tests.ts b/types/koa__multer/koa__multer-tests.ts index afa37214f9..48d6d011c6 100644 --- a/types/koa__multer/koa__multer-tests.ts +++ b/types/koa__multer/koa__multer-tests.ts @@ -13,6 +13,12 @@ const app = new Koa(); app.use(upload.single('avatar')); app.use(upload.array('photos', 12)); +app.use(async (ctx, next) => { + for (const file of ctx.request.files) { + console.info(`Received file: ${file.filename}`); + } + await next(); +}); const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]); app.use(cpUpload);