第一步:文件上传
编写upload方法
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->success('上传成功!');
$this->import($upload->rootPath . $info['file']['savepath']. $info['file']['savename']);
}
}
public function import($file){
$encoding=detect_encoding($file);
实现格式的转化
public function import($file){ $encoding=detect_encoding($file); //如果不是utf8格式,则转化为utf8 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){ $fields=array('no','name','sex'); $model=M('student'); $arrNO= $model->getField('no',true); $arr=array(); // $file="./Public/file/student.txt"; // $fp2 = fopen($file, 'w'); while (($row=fgetcsv($fp,1000,","))!==false) { $row=array_combine($fields, $row); if(in_array($row['no'],$arrNO)){ $file="./Public/file/student.txt"; $str .= $row['no']."该学号已存在".PHP_EOL; file_put_contents($file,$str); // echo $row['no']."该学号已存在".'<br>'; }else{ $arr[]=$row; $arrNO[]=$row['no']; $file="./Public/file/student.txt"; $str .= $row['no']."该学号可以导入".PHP_EOL; file_put_contents($file,$str); } fwrite($fp2, $str); if(count($arr)==1000){ $model->addAll($arr); unset($arr); } } fclose($fp2); if(count($arr)>0){ $model->addAll($arr); } $this->show('添加成功','utf8'); $this->up($file); } // $file_name = "student.txt"; //下载文件名 // $file_dir = "./Public/file/"; //下载文件存放目录 //检查文件是否存在 }
文件的下载
public function up($file){$file_name = "student.txt"; //下载文件名
$file_dir = "./Public/file/"; //下载文件存放目录
//检查文件是否存在
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 ();
}
}