微信小程序结合nodejs利用koa框架实现文件提交
使用了lin-ui,在程序中使用需要先构建npm包。
<l-button l-class="btn" size="long" bind:lintap="onChooseMessageFile">获取文件</l-button>
{
"usingComponents": {
"l-button":"/miniprogram_npm/lin-ui/button/index"
}
}
.btn{
margin-bottom: 20rpx !important;
}
wx.chooseMessageFile实现文件选择,wx.chooseImage实现图片上传,实现方法稍作修改即可
onChooseMessageFile(){
var that = this;
wx.chooseMessageFile({
count: 1,
type:'file',
success(res){
var filename = res.tempFiles[0].name;
console.info(filename);
that.setData({filename:filename});
console.log(res)
wx.uploadFile({
filePath: res.tempFiles[0].path,
name: 'img',
method:'POST',
url: 'http://localhost:3002/v1/file/upload',
success(res){
console.log(res.data)
}
})
}
})
}
node.js服务端代码
启动koa需要一个入口文件,继续使用koa需要将其实例化new ,其他插件的使用需要use.
const Koa = require('koa')
const koaBody=require("koa-body")
const Static=require("koa-static")
const Router = require('koa-router')
const fs = require('fs')
const app = new Koa()
app.use(koaBody({multipart:true}));
app.use(Static(__dirname+"D:/koa/dd/uploads/"))
app.listen(3002)
const router = new Router({
prefix:"/v1/file"
})
router.post("/upload",async (ctx)=>{
ctx.body = await upload()
function upload(){
return new Promise((resovle,rejects)=>{
console.log(2)
const file = ctx.request.files.img; // 获取上传文件img是name的key值
// 创建可读流
const reader = fs.createReadStream(file.path);
let filePath ="D:/koa/dd/uploads/"+file.name;//建议使用绝对路径
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
console.log(file)
resovle({msg:file})
})
}
//ctx.body=await upload()//异步等待当执行输出结果才释放函数
})
module.exports = router