Skip to content

Instantly share code, notes, and snippets.

Created December 24, 2018 06:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Using koa to handle file upload
const fs = require('fs')
const app = new Koa()
const router = new Router()
const serve = require('koa-static')
const koaBody = require('koa-body')
.use(serve(__dirname + '/files')) // files文件夹用于保存上传的文件,也是静态资源地址
// 前端使用formData方式组装数据'/api/upload-files', koaBody({ jsonLimit: '2mb', multipart: true }), async (ctx) => {
const data =;
const savePath = path.join(`./files`,
const reader = fs.createReadStream(data.path)
const writer = fs.createWriteStream(savePath)
const pro = new Promise( (resolve, reject) => {
var stream = reader.pipe(writer);
stream.on('finish', function () {
ctx.response.body = await pro
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment