微信小程序PHP之图片多图,单图实时上传。外加微信图片安全检测

思路:
wx.chooseImage拉起上传图片获取图片的本地路径
wx.uploadFile把本地路径等参数提交到指定的上传文件
在这里插入图片描述
在这里插入图片描述

<view class="shangchuan _tu">
	<block wx:for="{{formDatas.list[0].tempFilePaths}}" wx:for-item="item" wx:for-index="idx" wx:key="key">
		<view class="li">
			<image src="{{item}}"></image>
		</view>
	</block>
</view>
<view class="shangchuancc" bindtap="onPinlunImgAddHetong" data-idx="0">点击上传</view>
.shangchuan {
	display: flex;
	align-items: center;
	justify-content: center;
}

.shangchuan .li {
	width: 20%;
	height: 100rpx;
}

.shangchuan .li image {
	width: 100%;
	height: 100%;
}

.shangchuancc{
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 40rpx;
}

自定义函数文件:

/*
 * 上传文件2.0
 * app统一配置文件
 * count上传图片数量
 * idx当前第几个上传按钮
 */
function onPinlunImgAddHetongcc(app, that, count, idx) { //2.0
  if (count > 9) {
    wx.showModal({
      title: '提示',
      content: '最多只能上传9张',
      showCancel: false
    })
    return;
  }
  var formDatas = that.data.formDatas;
  var list = formDatas["list"];
  if ("undefined" == typeof list[idx]) {//定义存储数组
    list[idx] = {
      pic: [],
      tempFilePaths: [],
    };
  }
  wx.chooseImage({
    count: count, // 图片最多可以选择9张,默认9
    sizeType: ['compressed'], // 'original', 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success(res) { //获取当前虚拟地址
      list[idx].tempFilePaths = list[idx].tempFilePaths.concat(res.tempFilePaths);
      //上传图片
      for (var ic = 0; ic < res.tempFilePaths.length; ic++) {
        wx.showLoading({//上传图片提示
          title: '上传图片[' + (ic + 1) + '/' + res.tempFilePaths.length + ']',
          mask: true
        })
        wx.uploadFile({
          url: app.globalData.swtBase + "upload_file.php?act=shanghchuan", //上传文件路径
          filePath: res.tempFilePaths[ic],
          name: 'upFile',
          header: {
            'userToken': wx.getStorageSync('userToken') || '',
            'content-type': 'multipart/form-data'
          },
          success(res) {
            wx.hideLoading();
            var data = JSON.parse(res.data);
            if (data.code == 500) { //错误返回提示
              wx.showModal({
                title: '提示',
                content: data.msg,
                showCancel: false
              })
              return;
            } else {
              list[idx].pic = list[idx].pic.concat(data.pic);
              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 2000 //持续的时间
              })
              that.setData({
                formDatas: formDatas
              });
            }
          },
          fail: function (err) {
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '服务端错误',
              showCancel: false,
              complete: function () {
                //关闭当前页面
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          },
        })
      }
    }
  })
}

index.js使用

	onPinlunImgAddHetong: function (event) {
		var that = this;
		var idx = event.currentTarget.dataset.idx;
		var formDatas = that.data.formDatas;
		util.onPinlunImgAddHetongcc(app, that, 3, idx);
	},

upload_file.png
注意:牵扯待image文件夹路径,自行调整!!!!!!!!!

//sleep(1);
//判断是否有上传文件
if($act=='shanghchuan' && empty($_FILES) === false){
    if (!empty($_FILES['fileUrl']['error'])) {
        switch ($_FILES['fileUrl']['error']) {
            case '1':
                $error = '超过php.ini允许的大小。';
                break;
            case '2':
                $error = '超过表单允许的大小。';
                break;
            case '3':
                $error = '文件只有部分被上传。';
                break;
            case '4':
                $error = '请选择文件。';
                break;
            case '6':
                $error = '找不到临时目录。';
                break;
            case '7':
                $error = '写文件到硬盘出错。';
                break;
            case '8':
                $error = 'File upload stopped by extension。';
                break;
            case '999':
            default:
                $error = '未知错误。';
        }
		$infoArray = array();
        $infoArray["code"] = 500;
        $infoArray["msg"] = $error;
        $infoArray["_POST"] = $_POST;
	 }else{
		$infoArray["code"] = 200;
		$infoArray["msg"] = "OK";
        $infoArray["_FILES"] = $_FILES;
//判断是否有上传文件
		if(!isset($_FILES)){
			$infoArray = array();
			$infoArray["code"] = 500;
			$infoArray["msg"] = '没选中文件';
			$infoArray["_POST"] = $_POST;
			$json = json_encode($infoArray, true);
			echo $json;
			exit;
		}
		$upload_max_filesize = ini_get('upload_max_filesize');
		$allowedExts = array("gif", "jpeg", "jpg", "png");//允许上传的图片后缀
		$name = $_FILES["upFile"]["name"];//获取当前上传图片名称的数组
		$count = count($name);//php7以后count获取当前上传个数
		for($i=0;$i<$count;$i++){
			$temp = explode(".", $_FILES["upFile"]["name"]);
			$extension = end($temp); 
			$Leibie = $_FILES["upFile"]["type"];
			if((($Leibie == "image/gif")
			|| ($Leibie == "image/jpeg")
			|| ($Leibie == "image/jpg")
			|| ($Leibie == "image/pjpeg")
			|| ($Leibie == "image/x-png")
			|| ($Leibie == "image/png"))
			&& ($_FILES["upFile"]["size"] < ($upload_max_filesize*1048576))  
			&& in_array($extension, $allowedExts)){//二次图片核验
				$ststime = date("Ymd",time());
				$Mingming = time().mt_rand(10, 999999).".".$extension;//重新定义的文件名称
				mkdirs_(''.dirname(dirname(dirname(__FILE__))).'/image/'.$ststime.'');//创建子目录
				if (file_exists("image/".$ststime."/".$Mingming)){
					$infoArray = array();
					$infoArray["code"] = 500;
					$infoArray["msg"] = '文件已经存在';
					$infoArray["_POST"] = $_POST;
					$json = json_encode($infoArray, true);
					echo $json;
					exit;
				}else{
					// 如果 image 目录不存在该文件则将文件上传到 image 目录下
					move_uploaded_file($_FILES["upFile"]["tmp_name"], dirname(dirname(dirname(__FILE__)))."/image/".$ststime."/".$Mingming);
					//图片安全
					if($_FILES["upFile"]["tmp_name"]){
						$filePath = dirname(dirname(dirname(__FILE__)))."/image/".$ststime."/".$Mingming;
						$infoArray["filePath"] = $filePath;
						$real_path=realpath($filePath);
						if ($real_path && file_exists($real_path)) {
							$obj = new CURLFile($real_path);
							$data = array(
								'media' => $obj
							);
							$url= "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" . $access_token . "";
							$res = curl_post($url,$data);
							$infoArray["res"] = $res;
							$res = json_decode($res,true);
							if($res["errcode"] == 87014){
								$infoArray = array();
								$infoArray["code"] = 500;
								$infoArray["msg"] = '内容含有违法违规内容';
								$infoArray["_POST"] = $_POST;
								$json = json_encode($infoArray, true);
								echo $json;
								exit;
							}else{
								$infoArray["pic"][0] = "image/".$ststime."/".$Mingming;
							}
						}
					}
				}
			}elseif($_FILES["upFile"]["size"] > ($upload_max_filesize*1048576)){
				$infoArray = array();
				$infoArray["code"] = 500;
				$infoArray["msg"] = '超出服务器限制大小'.$upload_max_filesize.'';
				$infoArray["_POST"] = $_POST;
				$json = json_encode($infoArray, true);
				echo $json;
				exit;
			}else{
				$infoArray = array();
				$infoArray["code"] = 500;
				$infoArray["msg"] = '非法的文件格式';
				$infoArray["_POST"] = $_POST;
				$json = json_encode($infoArray, true);
				echo $json;
				exit;
			}
		}
	}
}
$json = json_encode($infoArray, true);
echo $json;
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值