微信小程序怎么给数据库的一个记录里新增图片数据?

news/2024/7/20 1:13:21 标签: 微信小程序, 小程序

前端代码:

<view class="row">
        <view class="text1">证件照:</view>
        <image class="zp"  src="{{zjz}}" mode="aspectFill" name="zhengjianzhao"></image>
        <button class="upload-img-btn" bindtap="chooseImg" type='primary'>拍照  / 上传</button>
    </view>  

js代码:

// pages/xggrzl/xggrzl.js
const db = wx.cloud.database()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openid: '',
    userInfo: '',
    array: ["大一", "大二", "大三", "大四"],
    array1: ["计算机科学与工程学院", "电子信息工程学院"],
    xy_index: 0,
    nj_index: 0,
    imgs:[],
    zjz: '',
    img: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const app = getApp()
    var openid = app.globalData.openid
    this.setData({
      openid: openid
    })
    db.collection("user").where({ openid: this.data.openid }).get().then(res => {
      console.log(res.data)
      this.setData({
        userInfo: res.data
      })
      console.log(this.data.userInfo[0].nj)
      for (let i = 0; i < this.data.array.length; i++) {
        if (this, this.data.array[i] == this.data.userInfo[0].nj) {
          console.log(i)
          this.setData({
            nj_index: i
          })
        }
      }
      for (let i = 0; i < this.data.array1.length; i++) {
        if (this, this.data.array1[i] == this.data.userInfo[0].xy) {
          console.log(i)
          this.setData({
            xy_index: i
          })
        }
      }
    })
  },

  // 上传一张图片
  chooseImg: function (e) {
    /* const app = getApp()
     var openid = app.globalData.openid
     this.setData({
       openid: openid
     })
     db.collection("user").where({ openid: this.data.openid }).get().then(res => {
       console.log(res.data)
       this.setData({
         userInfo: res.data
       })
       if(res.data.openid==app.globalData.openid){
         */
    var that = this;
    let openid = app.globalData.openid || wx.getStorageSync('openid');
    console.log(openid)
    // const filepath=this.data.img
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        console.log(res.tempFilePaths)
        let filePath = res.tempFilePaths[0]
        wx.cloud.uploadFile({
          cloudPath: (new Date()).valueOf() + '.png',//文件名 //云存储图片名字
          filePath,//临时路径:filepath
          success: res => {
            console.log('[上传图片] 成功:', res)
            console.log(res.fileID)
            that.setData({
              img: res.fileID,//云存储图片路径,可以把这个路径存到集合,要用的时候再取出来
              // zjz:res.tempFilePaths
              zjz: res.fileID
            })
            let fileID = res.fileID;
            // that.upload(res.fileID);
            db.collection("user").add({
              data: {
               zjz: fileID//数据库会新增一个记录
              //  zjz:filePath//数据库不会新增一个记录
              // zjz:this.data.concat(filePath)
              }
            })
          },
          fail: err => {
            // handle error
          }
        })
        // }
        // })
      }
    })

  },

  /* upload(filepath) {
     console.log(filepath)
     db.collection("user").add({
       data: {
         zjz: filepath,
       }
     }).then(res => {
       wx.showToast({
           title: '添加成功',
           icon: 'success',
           duration: 2000
       })
   })
   }
 })
 // const db = wx.cloud.database();
*/



  /*chooseImg: function (e) {
    var that = this;
    const app = getApp()
    var openid =app.globalData.openid
    // let openid = app.globalData.openid || wx.getStorageSync('openid');
    wx.chooseImage({
      // filePath: filePath, // 文件路径
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        console.log(res.tempFilePaths)
      //   const tempFilePaths=res.tempFilePaths
        // tempFilePath可以作为img标签的src属性显示图片
        let filePath = res.tempFilePaths[0]
        // const name = Math.random() * 1000000;
      //  const cloudPath = name + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath: "证件照",//文件名 //云存储图片名字
         filePath: filePath,//临时路径
          success: res => {
            console.log('[上传图片] 成功:', res)
           console.log(res.fileID)
           that.setData({
              zjz: res.fileID,//云存储图片路径,可以把这个路径存到集合,要用的时候再取出来
              // zjz:res.tempFilePaths
            })
          }
      })
            let fileID = res.fileID;
            //把图片存到user集合表
            const db = wx.cloud.database();
            // db.collection("user").where({openid:app.globalData.openid}).get().then(res=>{
            //   console.log(res)
              db.collection("user").add({
                data: {
                  // zjz: this.data[0],
                  zjz:fileID
                }, 
              })
            // })
           
          //     success: function () {
          //       wx.showToast({
          //        title: '图片存储成功',
          //         'icon': 'success',
          //         duration: 3000
          //       })
          //     },
          //     fail: function () {
          //       wx.showToast({
          //         title: '图片存储失败',
          //         'icon': 'none',
          //        duration: 3000
          //       })
          //     }
          //   });
          // },
          // fail: e => {
          //   console.error('[上传图片] 失败:', e)
          // },
          // complete: () => {
          // }
        // })
      }  
      // },
    })
  },
  */
 
 /* chooseImg: function (e) {
  var that = this;
  var imgs = this.data.imgs;
  if (imgs.length >= 9) {
    this.setData({
      lenMore: 1
    });
    setTimeout(function () {
      that.setData({
        lenMore: 0
      });
    }, 2500);
    return false;
  }
  wx.chooseImage({
    // count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
      // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths;
      var imgs = that.data.imgs;
      // console.log(tempFilePaths + '----');
      for (var i = 0; i < tempFilePaths.length; i++) {
        if (imgs.length >= 9) {
          that.setData({
            imgs: imgs
          });
          return false;
        } else {
          imgs.push(tempFilePaths[i]);
        }
      }
      // console.log(imgs);
      that.setData({
        imgs: imgs
      });
    }
   
  });
},
// 删除图片
deleteImg: function (e) {
  var imgs = this.data.imgs;
  var index = e.currentTarget.dataset.index;
  imgs.splice(index, 1);
  this.setData({
    imgs: imgs
  });
},
*/
  bindchangenj: function (e) {
    console.log(e.detail.value)
    this.setData({
      nj_index: e.detail.value
    })
  },
  bindchangexy: function (e) {
    console.log(e.detail.value)
    this.setData({
      xy_index: e.detail.value
    })
  },

  formSubmit(e) {
    console.log(e)
    db.collection("user").where({ openid: this.data.openid }).update({
      data: {
        nj: this.data.array[this.data.nj_index],
        phone: e.detail.value.phone,
        username: e.detail.value.name,
        xy: this.data.array1[this.data.xy_index],
        studentid: e.detail.value.xh,
        // tx:e.detail.value.userphoto,
        // zhengjianzhao: e.detail.value.zjz,
        // zhengjianzhao:e.data.imgs,
        _updateTime: Date.parse(new Date()),
      },
      success: function (res) {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500,
          success: function () {
            wx.navigateTo({
              url: '../grzl/grzl',
            })
          }
        })
      }
    })
  },

  // 上传多张图片
  // chooseImg: function (e) {
  //   var that = this;
  // var imgs = this.data.imgs;
  // if (imgs.length >= 9) {
  //   this.setData({
  //     lenMore: 1
  //   });
  //   setTimeout(function () {
  //     that.setData({
  //       lenMore: 0
  //     });
  //   }, 2500);
  //   return false;
  // }
  // wx.chooseImage({
  //   count: 1, // 默认9
  //   sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  //   sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  //   success: function (res) {
  // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
  // var tempFilePaths = res.tempFilePaths;
  // var imgs = that.data.imgs;
  // console.log(tempFilePaths + '----');
  // for (var i = 0; i < tempFilePaths.length; i++) {
  //   if (imgs.length >= 9) {
  // console.log(res)
  //   that.setData({
  //     // imgs: imgs
  //     zjz:res.tempFilePaths[0]
  //   });
  // return false;
  // } else {
  //   imgs.push(tempFilePaths[i]);
  // }
  // }
  // console.log(imgs);
  // that.setData({
  //   imgs: imgs
  // });
  // }
  //   })
  // },
  // 删除图片
  // deleteImg: function (e) {
  //   var imgs = this.data.imgs;
  //   var index = e.currentTarget.dataset.index;
  //   imgs.splice(index, 1);
  //   this.setData({
  //     imgs: imgs
  //   });
  // },
  // 预览图片
  // previewImg: function (e) {
  //   //获取当前图片的下标
  //   var index = e.currentTarget.dataset.index;
  //   //所有图片
  //   var imgs = this.data.imgs;
  //   wx.previewImage({
  //     //当前显示图片
  //     current: imgs[index],
  //     //所有图片
  //     urls: imgs
  //   })
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

目前实现的效果
在这里插入图片描述
数据库中的记录如下:
在这里插入图片描述

每上传一次图片就会在数据库中增加一条记录,我希望上传一次之后它可以添加到user数据库中的第一条记录中(第一条记录有zjz这个字段)
在这里插入图片描述
求问怎么把获取到的这个“zjz”字段放进去userinfo记录中?

20220331上午更新:
昨晚睡前也还是查了很多资料,回宿舍路上想到我应该在更新中直接上传就可以,所以把插入数据库操作注释掉了,然后一直试更新操作中的数据,突然就成功写入数据库了。
js代码:

// 上传一张图片
  chooseImg: function (e) {
    /* const app = getApp()
     var openid = app.globalData.openid
     this.setData({
       openid: openid
     })
     db.collection("user").where({ openid: this.data.openid }).get().then(res => {
       console.log(res.data)
       this.setData({
         userInfo: res.data
       })
       if(res.data.openid==app.globalData.openid){
         */
    var that = this;
    let openid = app.globalData.openid || wx.getStorageSync('openid');
    console.log(openid)
    // const filepath=this.data.img
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        console.log(res.tempFilePaths)
        let filePath = res.tempFilePaths[0]
        // 上传图片
        wx.cloud.uploadFile({
          cloudPath: (new Date()).valueOf() + '.png',//文件名 //云存储图片名字
          filePath,//临时路径:filepath
          success: res => {
            console.log('[上传图片] 成功:', res)
            console.log(res.fileID)
            that.setData({
              img: res.fileID,//云存储图片路径,可以把这个路径存到集合,要用的时候再取出来
              // zjz:res.tempFilePaths
              // zjz: res.fileID
            })
            // let fileID = res.fileID;
            // that.upload(res.fileID);//如果存在这句话,下文用zjz:fileID数据库也不会新增记录
            // db.collection("user").add({
              // data: {
              //  zjz: fileID//数据库会新增一个记录
              //  zjz:filePath//数据库不会新增一个记录
              // zjz:this.data.concat(filePath)
              // }
            // })
          },
          fail: err => {
            // handle error
          }
        })
        // }
        // })
      }
    })

  },
formSubmit(e) {
    console.log(e.detail.value)
    db.collection("user").where({ openid: this.data.openid }).update({
      data: {
        nj: this.data.array[this.data.nj_index],
        phone: e.detail.value.phone,
        username: e.detail.value.name,
        xy: this.data.array1[this.data.xy_index],
        studentid: e.detail.value.xh,
        // tx:e.detail.value.userphoto,
        zjz:this.data.img,
        // zhengjianzhao:e.data.imgs,
        _updateTime: Date.parse(new Date()),
      },
      success: function (res) {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500,
          success: function () {
            wx.navigateTo({
              url: '../grzl/grzl',
            })
          }
        })
      }
    })
  },

前端

<view class="row">
        <view class="text1">证件照:</view>
        <image class="zp"  src="{{userInfo[0].zjz}}" mode="aspectFill" name="zjz"></image>
        <button class="upload-img-btn" bindtap="chooseImg" type='primary'>拍照  / 上传</button>
    </view>  

实现的效果:在这里插入图片描述


http://www.niftyadmin.cn/n/927511.html

相关文章

怎么让微信小程序的时间选择器第一个日期是当前日期

问题&#xff1a; 我想知道这个日期要怎么赋值给start&#xff1f; 目前我的代码&#xff1a; js文件&#xff1a;&#xff08;onload函数里写的&#xff09; //获取系统当前日期年月日let riqi new Date();let timenew Date();//年var Y riqi.getFullYear();//月var M (ri…

success: function ()和success: res=> ()有什么区别

success: function ()和success: res> ()有什么区别 问题来源&#xff1a; 扫码签到的时候签到成功了&#xff0c;但是没有提醒图标&#xff08;写了代码&#xff09;&#xff0c;仔细对比了一下up的代码&#xff0c;发现了一点点区别: up代码 我一开始写的是这个 改成up…

django连接数据库获取数据

1、创建项目 执行代码 django-admin startproject myweb2、创建应用 python manage.py startapp myapp3、运行项目 python manage.py runserver如果没有加端口号就是默认8080&#xff0c;可以自己加端口号&#xff0c;防止与其它项目的端口号重复导致不能运行成功 python …

拼场功能的实现与错误

20220508答辩结束&#xff0c;希望不要二辩。 新写的云函数打印出来的数据是空的&#xff0c;云端测试是获取成功数据的。这两个key值我是根据联合查询的连接字段写上去的&#xff0c;本来只是试试&#xff0c;没想到成功了。 云函数的测试成功了&#xff0c;证明不是云函数…

场地预约管理微信小程序开发过程中的错误记录

2022.05.08答辩结束&#xff0c;希望一辩通过&#xff01; 前言 这篇文章是参考b站up主的图书馆预约小程序写的。 up主B站主页 欢迎各位去看一下。 一、获取到用户信息但是页面上没有显示 &#xff08;1&#xff09;原因&#xff1a;在前端wxml页面没有进行数据绑定&#x…

实现死锁检测

根据百度百科对于死锁的定义: 死锁是指两个或两个以上的进程在执行过程中&#xff0c;由于竞争资源或者由于彼此通信而造成的阻塞的现象&#xff0c;若无外力作用&#xff0c;它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁&#xff0c;这些永远在互相等待的进…

初识GoogleTest

1 初识GoogleTest 首先要了解googletest是做什么的&#xff0c;主要是单元测试框架。第二是googletest有什么优势&#xff1a; 测试过程独立可以重复&#xff1b;测试组织与代码结构保持比较好的一致性&#xff1b;支持跨平台&#xff1b;失败后能够提供完整错误信息&#xf…

1.Nginx安装和配置

Ubuntu18.04 Nginx安装和配置 1 源码下载: 具体最新版本见:http://nginx.org/en/download.html wget http://nginx.org/download/nginx-1.21.1.tar.gz 2 解压安装 下载源码后,直接进入nginx根目录进行编译安装,整个过程比较顺利没有报错 tar -zxvf nginx-1.21.1.tar.gz cd n…