busboy模块
busboy模块是用来解析POST请求的,Node原生req中的文件流,官方文档:https://github.com/mscdex/busboy
例子代码: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
45const Koa = require('koa2')
const path = require('path')
const app = new Koa()
//const bodyParser = require('koa-bodyparser)
const{ uploadFile } = require('./busboy.js')
//app.use(bodyParser())
app.use(async (ctx)=>{
if(ctx.url === '/' && ctx.method === 'GET'){
//当GET请求时候返回表单页面
let html = `
<h1>koa2 upload demo</h1>
<form method="POST" action="/upload.json" enctype="multipart/form-data">
<p>file upload</p>
<span>picName:</span><input name="picName" type="text" /><br/>
<input name="file" type="file" /><br/><br/>
<button type="submit">submit</button>
</form>
`
ctx.body = html
}else if(ctx.url === '/upload.json'&& ctx.method === 'POST'){
//上传文件请求处理
let result = {success:false}
let serverFilePath = path.join(__dirname,'uplaod-files')
//上传文件事件
result = await uploadFile(ctx,{
fileType:'album',
path:serverFilePath
})
ctx.body = result
}else{
//其他请求显示404
ctx.body = '404'
}
})
app.listen(3000,()=>{
console.log('busboy is running ')
})
1 | const inspect = require('util').inspect |
koa-multer
koa-body
未完待续……….
评论加载中