0

    小程序+egg

    2023.06.04 | admin | 141次围观

    写过一个约拍微信小程序的项目js上传图片到项目服务器上,这整个项目都是以展示图片,上传图片为主,所以这个项目的核心就是需要有个图片服务器,如果无法实现在小程序上传图片到服务器,再从图片服务器获取图片返回前端展示,那么这个约拍小程序项目就无法实现。

    虽然可以使用第三方的图片服务器,比如:七牛,但是由于我是小型项目js上传图片到项目服务器上,毕业设计演示的地方网络很大概率很很差,所以使用第三方图片服务器不大可行,所以我构建的图片服务器是本地服务器。

    实现流程为:

    1.小程序实现前端上传图片

    2.小程序向图片服务器发送请求储存图片;

    3.后端返回成功存储图片的路径,当所有图片都上传成功的时候,小程序再发送请求,把约拍相关的所有信息存进数据库,

    数据库存储的是图片在服务器的路径;

    4.当前端需要在展示图片的时候,直接通过后端返回的图片路径,通过img标签的src属性加载就行了,不过要记得加上后端运行项目的对应地址。因为我后端项目运行的地址是在端口7001,所以路径写法如下:

        

    实现效果如下:

    后端成功接收并存储图片:

    小程序+egg

    1.在egg.js 中要实现图片的存储,需要引入一个文件的读写插件

    npm i await-stream-ready, stream-wormhole -S
    

    2.配置访问地址router.js,注意要使用POST请求

    router.post('/api/uploads',controller.home.uploadImg);

    3.编写controller控制器home.js

    const Controller = require('egg').Controller;
    //文件存储
    const fs=require('fs');
    const path=require('path');
    const awaitWriteStream=require('await-stream-ready').write;
    const senToWormhole=require('stream-wormhole');
    class HomeController extends Controller {
      //  上传头像图片
      async uploadImg(){
        const ctx = this.ctx;
        //获取前端的文件流
        const stream=await ctx.getFileStream();
        let uid=stream.fieldname;
        //console.log("1111111",uid);
        // random.getRandomString(8);
        //文件名:随机数+时间戳+原文件后缀
        // path.extname(stream.filename).toLocaleLowerCase()为后缀名(.jpg,.png等)
        const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
        // 同步读取文件
        var files = fs.readdirSync('app/public/'+uid+'/img');//读取该文件夹
        files.forEach(function(file){
        var stats = fs.statSync('app/public/'+uid+'/img'+'/'+file);
              if(stats.isDirectory()){
              emptyDir('app/public/'+uid+'/img'+'/'+file);
            }else{
              fs.unlinkSync('app/public/'+uid+'/img'+'/'+file); 
              console.log("删除文件"+'app/public/'+uid+'/img'+'/'+file+"成功");
              }   
            })
            let target = path.join(this.config.baseDir, 'app/public/'+uid+'/img', filename);
            let imgurl='public/'+uid+'/img';
        
            // 生成一个文件写入 文件流
            const writeStream = fs.createWriteStream(target);
            try {
                // 异步把文件流 写入
                await awaitWriteStream(stream.pipe(writeStream));
            } catch (err) {
                // 如果出现错误,关闭管道
                await sendToWormhole(stream);
                throw err;
            }
        ctx.body = {
          code:200,
          data:{
                imgurl
              }
        };
      }
    }
    module.exports = HomeController;

    4.小程序官方文档有对应支持图片上传的API

    1、微信小程序选择图片wx.chooseImage()接口的使用

    2、微信小程序上传文件接口wx.uploadFile()的使用

    HTML代码

        
          
            
          
          
            
          
        

    css代码

    .form-first-bottom{
      margin-left:30rpx;
      margin-right:20rpx;
      margin-top:40rpx;
      padding-bottom:40rpx;
      width:clac(100% - 50rpx);
      display:flex;
      flex-wrap:wrap;
    }
    .add-container{
      width:calc(34% - 18rpx);
      height:200rpx;
      text-align: center;
      line-height: 260rpx;
      padding-top:13rpx;
      padding-right:13rpx;
    }
    .form-first-bottom>.add-container:nth-of-type(3n){ /* 选择个数是3的倍数的元素 */
      padding-right: 0;
    }
    .selectclass1{
      width:100%;
      height:100%;
    }

    js代码:

      //上传图片
      upImgClick: function (e) {
       var that=this;
        wx.chooseImage({
          count: 9,                                           //一次上传图片数量
          sizeType: ['compressed'],                           //图片大小
          sourceType: ['album', 'camera'],
          success: function (res) {
            // util.showBusy('正在上传')
            var filePath = res.tempFilePaths;
            that.setData({ upimgarr: filePath});
            console.log("上传图片", filePath);            //获取图片路径
          },
          fail: function (e) {
            console.error(e)
          }
        })
      },
          // 上传图片到后端服务器
            wx.uploadFile({
              url: util.pictureurl +'api/uploads',                  //服务器接口地址
              filePath: that.data.upimgarr[i],
              name: uid+"#"+that.data.bid+"#"+i,
              success: function (res) {
                // util.showSuccess('上传图片成功')
              }, complete: function (complete) {
                console.log("com",complete)
                i++;
                // 当图片都上传成功的时候就可以提交表单
                if (i == that.data.upimgarr.length) {
                  let dd = JSON.parse(complete.data);
                  data.imgurl = dd.data.imgurl;
                  util.showSuccess('上传图片成功')
                  api.addSave(util.pictureurl +'addBeat',data).then(res => {
                    if(res==1)
                    wx.navigateTo({
                      url: '../../wantBeathim/addSuccess/addSuccess',
                    })
                  })
                } else if (i < that.data.upimgarr.length) {      //若图片还没有传完,则继续调用函数
                  that.up()
                }
              },
              fail: function (e) {
                util.showModel('上传图片失败')
                console.error(e);
              }
            })

    版权声明

    本文仅代表作者观点。
    本文系作者授权发表,未经许可,不得转载。

    发表评论