Skip to content

Instantly share code, notes, and snippets.

@bulatie
Last active October 31, 2019 03:11
Show Gist options
  • Save bulatie/9067c6a25958d976fde34544f5dc8938 to your computer and use it in GitHub Desktop.
Save bulatie/9067c6a25958d976fde34544f5dc8938 to your computer and use it in GitHub Desktop.
koa upload file
const fs = require('fs')
const path = require('path')
const os = require('os')
const Koa = require('koa')
const koaBody = require('koa-body');
const app = new Koa()
async function wait(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
app.use(koaBody({
multipart: true
}));
app.use(async ctx => {
if ('POST' === ctx.method && ctx.url === '/api/upload') {
const timeoutDuration = 1000 * 5
const files = ctx.request.files.path;
let name = []
if (files.length > 1) {
for (const file of files) {
const reader = fs.createReadStream(file.path);
const stream = fs.createWriteStream(path.join(__dirname + '/upload/', file.name));
reader.pipe(stream);
name.push(file.name)
await wait(timeoutDuration)
console.log('uploading %s -> %s', file.name, stream.path);
}
} else {
const reader = fs.createReadStream(files.path);
const stream = fs.createWriteStream(path.join(__dirname + '/upload/', files.name));
reader.pipe(stream);
name.push(files.name)
await wait(timeoutDuration)
console.log('uploading %s -> %s', files.name, stream.path);
}
ctx.body = {
name: name
}
}
})
app.listen(port, host)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment