TP 文件上传 防止数据重复 ,数据下载

1.写入upload方法,获取展示页面,实例化上传类,设置附件上传大小,设置附件上传根目录,设置附件上传子目录,
public function upload(){
		if (IS_GET) {
			$this->display();
			exit;
		}
		$upload = new \Think\Upload();//实例化上传类
		$upload->maxSize = 0;//设置附件上传大小
		$upload->exts = array('csv');//设置附件上传类型
		$upload->rootPath = './Public/Upload/';//设置附件上传根目录
		$upload->savePath = '';//设置附件上传(子)目录
		//上传文件
		$info = $upload->upload();
		if(!$info){ //上传错误提示信息
			$this->error($upload->getError());
		}else{//上传成功
			// $this->success('上传成功!');
			// $info['file']['savepath'].$info['file']['savename'],'utf8';
			$this->import($upload->rootPath . $info['file']['savepath'] . $info['file']['savename']);
		}
	}


2.写入import方法


public function import($file){
		// $file = "./Public/Upload/2018-03-21/5ab306a982935.csv";
		//检测文件编码
		$encoding = detect_encoding($file);
		// dump($encoding);
		// exit;

		//如果不是utf8格式,则转化为utf8
		// if ($encoding != 'UTF-8') {
		// 	$contens = file_get_contents($file);//适合小文件(10M以内)
		// 	$contens = mb_convert_encoding($contens, 'utf-8',$encoding);
		// 	file_put_contents($file,$contens);//保存
			
		// }

		if ($encoding != 'utf-8') {
            $contens = file_get_contents($file);
            $contens = mb_convert_encoding($contens,'utf-8',$encoding);
            file_put_contents($file, $contens);
        }
		// dump('ok');
		// exit;

		//解析csv
         $fp = fopen($file,'r');
        if($fp){
            $fileds = array('no','name','sex');
            $model = M('newstudent');
          

            $arrNo = $model->getField('no',true);
            $arr = array();
            while(($row = fgetcsv($fp,1000,",")) !== false) {
                $row = array_combine($fileds, $row);  

                if (in_array($row['no'], $arrNo)) {
                    //存在
                    echo $row['no'] . '已经存在<br>';
                }else{
                    //不存在
                    $arrNo[] = $row['no'];
                    $arr[] = $row;
                }
                if (count($arr) == 1000) {
                    $model->addAll($arr);
                    unset($arr);
                }

            }//while end
                if (count($arr)>0) {
                    $model->addAll($arr);
                }
                $this->show('添加成功','utf8');

            }

        } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值