导入文件
程序员文章站
2024-02-19 11:06:04
...
导入文件:实例化上传类,设置附件上传大小,上传类型,上传文件
public function upload(){
$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->import($upload->rootPath.$info['file']['savepath'].$info['file']['savename']);
}
}
public function import($file){
$encoding=detect_encoding($file);
//如果不是utf-8转换utf-8
if($encoding!='UTF-8'){
$contents=file_get_contents($file);
$contents=mb_convert_encoding($contents,'utf-8', $encoding);
file_put_contents($file, $contents);
}
$fp=fopen($file, 'r');
if($fp){
$fields=array('no','name','sex');
$model=M('student');
$arrNO=$model->getField('no',true);
$arr = array();
while(($row = fgetcsv($fp,1000,","))!== false){
$row=array_combine($fields, $row);
// dump($data);
// exit;
$name = $row['name'];
$row['py'] = SpGetPinyin($name);
if(in_array($row['no'],$arrNO)){
$file = './Public/uploads/demo.txt';
$current .= $row['no']."已存在\r\n";
}else{
$arrNO[]=$row['no'];
$arr[]=$row;
$file = './Public/uploads/demo.txt';
$current .= $row['no']."导入成功\r\n";
}
if(count($arr)==1000){
$model->addAll($arr);
unset($arr);
}
}
if(count($arr)>0){
$model->addAll($arr);
}
$this->success("导入成功",'index');
}
file_put_contents($file, $current);
$file_name = "demo.txt";
$file_dir = "./Public/uploads/";
if(!file_exists($file_dir.$file_name)){
echo "文件找不到";
exit;
}else{
$file = fopen($file_dir.$file_name,"r");
Header("content-type:application/octet-stream");
Header("Accept-Ranges:bytes");
Header("Accept-Length:".filesize($file_dir.$file_name));
Header("Content-Disposition:attachment;filename=".$file_name);
echo fread($file,filesize($file_dir.$file_name));
fclose($file);
exit;
}
}
然后改变编码格式,改成UTF8样式,然后把表里的文件传到数组中,要循环判断,判断是否有重复的数据,进行报错或者成功。