安装插件
koa
npm install -s koa
koa-router
npm install -s koa-router
koa-body
npm install -s koa-body
我是习惯使用这些插件所以才安装的,其中重要得就是 koa-body 是用来解析form-data数据得。
实现代码
const Koa = require('koa');
const body = require("koa-body");
const router = require('koa-router')();
const utility = require("utility"); //用于md5 加密
const fs = require('fs');
const os = require('os');
const app = new Koa();
//用于解析 formData
router.use(body({multipart: true,}));
// 保存图片
router.post('/savaImage', (ctx, next) => {
//获取 multipart 中 formData 文件信息
let data = ctx.request.files.img;
//创建图片名称
let fileName = utility.md5 ((new Date()).getTime() + " ");
const render = fs.createReadStream(data.path);
let filePath = 'public/images/' + fileName + '.'+ data.name.split('.')[1];
// 创建写入流
const upStream = fs.createWriteStream(filePath);
render.pipe(upStream);
let address = os.networkInterfaces().WLAN[1].address;
filePath = "http://" + address + ":3000/" + filePath;
ctx.body = filePath
});
// 动态路由
// 获取图片 将图片转化成二进制发送给前端
router.get("/public/images/:imgName", (ctx,next) => {
let path = ctx.url.slice(1);
let data = fs.readFileSync(`${path}`,'binary');
ctx.res.writeHead('200');
ctx.res.write(data, 'binary');
ctx.res.end();
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log("server run: http://127.0.0.1:3000");
});
网友评论