您的位置:首页 > 编程语言 > PHP开发

ThinkPHP上传文件时如何除去重复值

2018-04-01 22:02 316 查看
上传文件时,首先要判断是不是 IS_GET()方式请求,然后实例化上传类,再设置上传的相关变量,最后判断文件是否上传,代码如下:public function upload(){
if(IS_GET){
$this->display();
exit;
}
$upload = new \Think\Upload();//实例化上传类
$upload->maxSize = 3145728;//上传文件大小
$upload->exts = array('csv');//设置附件上传类型
$upload->rootPath = './Public/Uploads/';//设置附件上传根目录
$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);
if ($encoding != 'UTF-8') {
$contens = file_get_contents($file);
$contens = mb_convert_encoding($contens, 'utf-8',$encoding);
file_put_contents($file, $contens);
}

$fp = fopen($file, 'r');
if ($fp) {
$fields = array('no','name','sex');
$model = M('student');
$arrNo = $model->getField('no',true);
$arr = array();
$filename = "./Public/Log/load.txt";
$f = fopen($filename, 'w');

while (($row = fgetcsv($fp,1000,","))!==false) {
$row = array_combine($fields, $row);
$name = $row['name'];
$row['py']=SpGetPinyin($name);
if (in_array($row['no'], $arrNo)) {
// echo $row['0']."已存在 . <br>";
$data .= $row['no'] . "已存在\r\n";
}else{
$arr[] = $row;
$arrNo[] = $row['no'];
$data .= $row['no'] . "导入成功\r\n";
}
if (count($arr)==1000) {
$model->addAll($arr);
unset($arr);
}
}

if (count($arr)>0) {
$model->addAll($arr);
}
$this->show('添加成功!','utf8');
}
$fwrite=fwrite($f,$data);

$file_name = "load.txt"; //下载文件名
$file_dir = "./Public/Log/"; //下载文件存放目录
//检查文件是否存在
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 ();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: