- res.jsonp(config.json)
- 给config.json的imageUrlPrefix加后端域
koa实现
这时个比较精巧的库,而且将在v3中去掉了generator写法,generator现在已经渐渐不被支持,所以使用async写法吧。我主要用了await-busboy这个库,实现文件处理。
实现判断
const ActionType = ctx.query.action
// 当ActionType为config时返回与express中一样的json
// 当为uploadimage或uploadfile时处理
处理上传
const parse = require('await-busboy')
const parts = parse(ctx)
let part,
stream,
tmp_name,
file_path,
filename
while ((part = await parts)) {
if (part.length) {
// 此处解析到form的fields
console.log({ key: part[0], value: part[1] })
} else {
// 此处解析到文件并以可读流形式返回,通过nodejs官方API存储
if(ActionType === 'uploadimage' && img_type.indexOf(path.extname(part.filename)) >= 0 ){
filename = 'pic_'+ (new Date()).getTime() + '_' + part.filename
file_path = path.join(img_path, filename)
} else if (ActionType === 'uploadfile'){
filename = 'file_'+(new Date()).getTime()+'_'+part.filename
file_path = path.join(files_path, filename)
}
stream = fs.createWriteStream(path.join(static_path,file_path))
part.pipe(stream)
tmp_name = part.filename
}
// 返回json要引用koa-jsonp哦~~
到这大概可以了,自己去试一下吧~~希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
