Koa2使用koa-body实现文件上传(Node可读流可写流)

koa-body文件上传自定义文件夹及文件名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const Koa = require('koa'),
//bodyParser = require('koa-bodyparser'),
router = require('koa-router')(),
stc = require('koa-static'),
render = require('koa-art-template'),
fs = require('fs'),
path = require('path');
const koaBody = require('koa-body');

//引入子模块

var admin = require('./routes/admin.js');
var api = require('./routes/api.js');
var index = require('./routes/index.js');

var app = new Koa();
//配置koa-art-template 模板引擎
render(app, {
root: path.join(__dirname, 'views'),
extname: '.html',
debug: process.env.NODE_ENV !== 'production',
minimize: true,
htmlMinifierOptions: {
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
// automatically merged at runtime: rules.map(rule => rule.test)
ignoreCustomFragments: []
}
});
//app.use(bodyParser());
app.use(stc(
path.join(__dirname, './statics')
))
app.use(stc(
path.join(__dirname, './public')
))
//koaBody
app.use(koaBody({
multipart: true, // 支持文件上传
encoding: 'gzip',
formidable: {
uploadDir: path.join(__dirname, 'public/upload/'), // 设置文件上传目录
keepExtensions: true, // 保持文件的后缀
maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小
onFileBegin: (name, file) => { // 文件上传前的设置
// console.log(`name: ${name}`);
// console.log(file);
},
}
}));
//配置路由
router.use(index);
/*
/admin 配置子路由 层级路由

/admin/user
*/
router.use('/admin', admin);
/*
/api/newslist 新闻列表的api
*/
router.use('/api', api); /*在模块里面暴露路由并且启动路由*/

router.post('/getData', async(ctx, next) => {

let request = ctx.request;
let req_query = request.query;
let req_querystring = request.querystring;
console.log(request, req_query, req_querystring);
console.log(ctx.request.body)
console.log(ctx.request.files);

ctx.cookies.set(
'MyName', 'Koa2', {
domain: '127.0.0.1', // 写cookie所在的域名
path: '/', // 写cookie所在的路径
maxAge: 1000 * 60 * 60 * 24, // cookie有效时长
expires: new Date('2018-12-31'), // cookie失效时间
httpOnly: false, // 是否只用于http请求中获取
overwrite: false // 是否允许重写
}
);
//ctx.status = 200
return ctx.body = {
code: 200,
data: {
arr: [1, 2, 3, 4]
}
};
})

router.post('/uploadPic', async(ctx, next) => {

const file = ctx.request.files.file; // 上传的文件在ctx.request.files.file
// 创建可读流
const reader = fs.createReadStream(file.path);
// 修改文件的名称
var myDate = new Date();
var newFilename = file.name.split('.')[0] + '_' + myDate.getTime() + '.' + file.name.split('.')[1];
var targetPath = path.join(__dirname, './public/upload/') + `/${newFilename}`;
//创建可写流
const upStream = fs.createWriteStream(targetPath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
//ctx.redirect('/')
//返回保存的路径
return ctx.body = {
code: 200,
data: {
url: 'http://' + ctx.headers.host + '/upload/' + newFilename
}
};
});

//启动路由
app.use(router.routes()).use(router.allowedMethods());

app.listen(12300);