0%
创建项目目录
mkdir uploadFile cd uploadFile
|
初始化项目
安装依赖
npm install koa koa-router koa-body koa-static
|
项目主程序 app.js
const Koa = require('koa'); const koaBody = require('koa-body'); const Router = require('koa-router'); const static = require('koa-static'); const cors = require('koa2-cors') const fs = require('fs'); const path = require('path');
const hostname = '127.0.0.1' const port = 3000
const app = new Koa() const router = new Router()
app.use(cors()) app.use(static('.'));
router .get('/', (ctx, next) => { ctx.body = 'hello world!' }) .post('/api/upload', koaBody({ multipart: true, formidable: { } }), (ctx, next) => { let file = ctx.request.files.file let fileType = file.name.split('.').pop() let fileName = `${Date.now()}.${fileType}` let fileReader = fs.createReadStream(file.path) let writeStream = fs.createWriteStream(path.join(__dirname, 'upload', `${fileName}`))
fileReader.pipe(writeStream) ctx.body = { code: 0, message: '上传成功', url: `http://${hostname}:${port}/upload/${fileName}` } })
app .use(router.routes()) .use(router.allowedMethods())
app.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); })
|