2021-03-03

微信小程序结合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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值