Created
December 24, 2018 06:58
-
-
Save li-wu/108fdae915eab4b2c872a46c2b1a2d35 to your computer and use it in GitHub Desktop.
Using koa to handle file upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const app = new Koa() | |
const router = new Router() | |
const serve = require('koa-static') | |
const koaBody = require('koa-body') | |
app | |
.use(serve(__dirname + '/files')) // files文件夹用于保存上传的文件,也是静态资源地址 | |
.use(router.routes()) | |
// 前端使用formData方式组装数据 | |
router.post('/api/upload-files', koaBody({ jsonLimit: '2mb', multipart: true }), async (ctx) => { | |
const data = ctx.request.body.files.data; | |
const savePath = path.join(`./files`, data.name) | |
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 () { | |
resolve(`http://<Server>${data.name}`); | |
}); | |
}) | |
ctx.response.body = await pro | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment