微信小程序选择多张图片连同表单中其他信息一起上传并保存到MySQL数据库

多读多写多记录,多学多练多思考。----------- Banana • Banuit Gang(BUG香柚帮)


  最近在做小程序的多图片上传+连同表单信息和图片服务器端地址一起保存到数据库中这项功能,但是发现小程序只支持一张一张的图片上传,即使用递归或者循环都必须调用多次上传图片的方法,如果上传图片时连同表单一块提交持久化到数据库,那么就会保存多条记录,想了又想,最终思路就是把上传图片和提交表单分为两个方法,首先上传多张图片,在PHP后端单张上传成功后,返回给小程序一个服务器图片地址,然后小程序把地址保存到一个全局数组里边,当选择的图片和上传成功的图片相等时,再把数据转化为json,然后连同表单其他信息再调用上传信息的方法,持久化到数据库中就可以了。这只是我的思路,不知道还有什么好的方法可以解决这个问题呢。

我单独整理了一个小栗子,大家可以下载学习一下,例子中包括填写表单,上传信息,展示信息

GitHub地址:https://github.com/kun19911227/minipro.git

upload_info.js

//点击添加按钮选择多张图片
chooseImage: function(e) {
   wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        if (this.data.images.length <= 1) {
          const images = this.data.images.concat(res.tempFilePaths)
          // 限制最多只能留下2张照片
          this.setData({
            images: images
          })
        } else {
          wx.showToast({
            title: '最多只能选择两张照片',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      }
   })
}
//上传图片和信息
upload_info: function() {
    var images_list = []; //设置了一个空数组进行储存服务器端图片路径
        
    for (var i = 0; i < this.data.images.length; i++) {
        var that = this;
        wx.uploadFile({
            url: 'http://tq.com/index.php?g=api&m=user&a=upload_img', //上传图片接口地址
            filePath: this.data.images[i],
            name: 'photo',
            formData: null,
            success: function(res) {
                // json转换数组
                var jsonObj = JSON.parse(res.data)
                images_list.push(jsonObj.url);//把每次返回的地址放入数组
                if (that.data.images.length == images_list.length) {//当选中的图片和上传成功图片相等时,调用上传信息方法
                    var photo = JSON.stringify(images_list)//将数组转化为json
                    wx.request({
                        url: 'http://tq.com/index.php?g=api&m=fastcar&a=upload_info',
                        method : 'POST',
                        data: {
                              name: that.data.name,
                              sex: that.data.sex == '男' ? 1 : 2,
                              age: that.data.age,
                              phone: that.data.phone,
                              id_number: that.data.idcard,
                              is_member:1,
                              condition: that.data.describe,
                              photo: photo,
                              expert_status: arr_str,
                              expert_units: that.data.unit,
                              expert_name: that.data.expert_name,
                              cons_start_date: that.data.date,
                              cons_end_date: that.data.date2,
                              require_status: that.data.requires
                        },
                        header: {
                            "Content-Type": "application/x-www-form-urlencoded" 
                        },
                        success(res) {

                        }  
                    }) 
                    //console.log(photo);
                }
            },
            fail: function(error) {
                console.log(error);
            }
        })
    }
}

 UserController.class.php

    /**
	 * 上传信息api
	 */
	public function upload_info() {
		$data = array();
		$post = array();
		//接收参数
		$post['name'] = I('post.name');
		$post['sex'] = I('post.sex');
		$post['age'] = I('post.age');
		$post['phone'] = I('post.phone');
		$post['id_number'] = I('post.id_number');
		$post['is_member'] = I('post.is_member');
		$post['condition'] = I('post.condition');
		$post['phpto'] = I('post.photo');
		$post['expert_status'] = I('post.expert_status');
		$post['expert_units'] = I('post.expert_units');//非必填
		$post['expert_name'] = I('post.expert_name');//非必填
		$post['cons_start_date'] = I('post.cons_start_date');
		$post['cons_end_date'] = I('post.cons_end_date');
		$post['require_status'] = I('post.require_status');
		$post['create_time'] = time();

		if ( (empty($post['user_id']) && isset($post['user_id'])) ||
			(empty($post['name']) && isset($post['name'])) ||
			(empty($post['sex']) && isset($post['sex'])) ||
			(empty($post['age']) && isset($post['age'])) ||
			(empty($post['phone']) && isset($post['phone'])) ||
			(empty($post['id_number']) && isset($post['id_number'])) ||
			(empty($post['is_member']) && isset($post['is_member'])) ||
			(empty($post['condition']) && isset($post['condition'])) ||
			(empty($post['rop']) && isset($post['rop'])) ||
			(empty($post['expert_status']) && isset($post['expert_status'])) ||
			(empty($post['cons_start_date']) && isset($post['cons_start_date'])) ||
			(empty($post['cons_end_date']) && isset($post['cons_end_date'])) ||
			(empty($post['require_status']) && isset($post['require_status'])) ) {
			$data['code'] = 0;
			$data['msg'] = "有必填参数为空";
		} else {

			$result = D('User')->add($post);

			if ($result !== false) {
				$data['code'] = 1;
				$data['msg'] = "提交成功";
			} else {
				$data['code'] = 2;
				$data['msg'] = "提交失败";
			}


		}
		return $this->ajaxReturn($data);
	}

	/**
	 * 上传图片
	 */
	public function upload_img() {
		$data = array();
		$uploadConfig = array(
			'FILE_UPLOAD_TYPE' => sp_is_sae() ? 'Sae' : 'Local',
			'rootPath' => './'.C( 'UPLOADPATH' ),
			'savePath' => './minipro/',
			'saveName' => array( 'uniqid', '' ),
			'exts' => array( 'jpg', 'jpeg', 'png','gif' ),
			'autoSub' => false
		);
		$upload = new \Think\Upload( $uploadConfig );
		$info = $upload->upload();
		if($info) {
			$save_name = $info['photo']['savepath'].$info['photo']['savename'];
			$save_name = substr($save_name,1);
			$url = "http://".$_SERVER['HTTP_HOST']."/data/upload".$save_name;
			$data['url'] = $url;
			return $this->ajaxReturn($data);
		}
	}

 

你可能感兴趣的:(小程序,PHP)