要实现文件的导入会有一个日志文件,日志文件则则会有一个状态,这个状态就会以文件的形式下载出来,从下列代码可以看出三个文件相互关联,实现导入,和下载
//导入
public function upload(){if (IS_GET) {
$this->display();
exit();
}
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 0 ;// 设置附件上传大小,0为不限大小
$upload->exts = array('csv');// 设置附件上传类型
$upload->rootPath = './Public/Uploads/'; // 设置附件上传根目录
$upload->savePath = ''; // 设置附件上传(子)目录
// 上传文件
$info = $upload->upload();
// dump($info);
// exit();
if(!$info) {
// 上传错误提示错误信息
$this->error($upload->getError());
}else{
// 上传成功 获取上传文件信息
// echo $upload->rootPath . $info['file']['savepath'] . $info['file']['savename'];
// $this->success('上传成功!','import');
$this->import($upload->rootPath . $info['file']['savepath'] . $info['file']['savename']);
}
}
//上传文件信息到数据表
public function import($file){
$encoding = detect_encoding($file);
if ($encoding != 'utf-8') {
$contens = file_get_contents($file);
$contens = mb_convert_encoding($contens,'utf-8',$encoding);
file_put_contents($file, $contens);
}
// exit();
$fp = fopen($file,'r');
if($fp){
$fileds = array('no','name','sex');
$model = D('student');
$arrNo = $model->getField('no',true);
$arr = array();
while(($row = fgetcsv($fp,1000,",")) !== false) {
$row = array_combine($fileds, $row);
$row['py'] = SpGetPinyin($row['name']);
if (in_array($row['no'], $arrNo)) {
//存在
$file = './Public/Download/demo.txt';
$current .= $row['no'] . '已经存在,';
file_put_contents($file, $current);
}else{
//不存在
$arrNo[] = $row['no'];
$arr[] = $row;
$file = './Public/Download/demo.txt';
$current1 .= $row['no'] . '导入成功,';
file_put_contents($file, $current1);
}
if (count($arr) == 1000) {
$model->addAll($arr);
unset($arr);
}
}
if (count($arr)>0) {
$model->addAll($arr);
}
$this->success('执行成功','index');
}
}
public function download(){
$file_name = 'demo.txt';
$file_dir = './Public/Download/';
//检查文件是否存在
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 ();
}
}