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');
}
}