From 2c96d1bccd56c27f30a23d4775c46a55f420cc49 Mon Sep 17 00:00:00 2001 From: Billchenchina Date: Wed, 30 May 2018 21:39:32 +0800 Subject: [PATCH 1/2] Fix: multiple files upload --- upload/app.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/upload/app.js b/upload/app.js index 1a01aec..62defd6 100644 --- a/upload/app.js +++ b/upload/app.js @@ -36,11 +36,21 @@ app.use(async function(ctx, next) { // ignore non-POSTs if ('POST' != ctx.method) return await next(); - const file = ctx.request.body.files.file; - const reader = fs.createReadStream(file.path); - const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString())); - reader.pipe(stream); - console.log('uploading %s -> %s', file.name, stream.path); + const files = ctx.request.body.files.file; + if (files instanceof Array) { + files.forEach(function(file, index) { + const reader = fs.createReadStream(file.path); + const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString())); + reader.pipe(stream); + console.log('uploading %s -> %s', file.name, stream.path); + }); + } else { + const file = files; + const reader = fs.createReadStream(file.path); + const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString())); + reader.pipe(stream); + console.log('uploading %s -> %s', file.name, stream.path); + } ctx.redirect('/'); }); From 070a9794fad41f1cbb3fc036cf2d4c5c99636b84 Mon Sep 17 00:00:00 2001 From: Billchenchina Date: Wed, 30 May 2018 22:05:02 +0800 Subject: [PATCH 2/2] Fix: use Array.isArray and not special-case --- upload/app.js | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/upload/app.js b/upload/app.js index 62defd6..0b067c3 100644 --- a/upload/app.js +++ b/upload/app.js @@ -36,21 +36,16 @@ app.use(async function(ctx, next) { // ignore non-POSTs if ('POST' != ctx.method) return await next(); - const files = ctx.request.body.files.file; - if (files instanceof Array) { - files.forEach(function(file, index) { - const reader = fs.createReadStream(file.path); - const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString())); - reader.pipe(stream); - console.log('uploading %s -> %s', file.name, stream.path); - }); - } else { - const file = files; + var files = ctx.request.body.files.file; + if (!Array.isArray(files)) { + files = new Array(files); + } + files.forEach(function(file, index) { const reader = fs.createReadStream(file.path); const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString())); reader.pipe(stream); console.log('uploading %s -> %s', file.name, stream.path); - } + }); ctx.redirect('/'); });