实现上传表单页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>文件上传</h1>
<form action="{:U('upload')}" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
在控制器里实现上传操作:upload方法
在上传文件时会遇到记录重复的问题,解决学号去重问题
将原有数据表中的所有学员存入一个数组$arrNo中,
读取文件中的一条数据,
检测该行中的学号在数组arrno中是否存在,如果不存在,写入二位数组$arr,并且把学号追加到arrNo中;如果存在则继续读取下一行
读取下一行...
public function upload(){
if(IS_GET){
$this->display();
}else{
$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);
//如果不是utf8格式,则转化为utf8
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('newstudent');
//解决学号去重问题
$arrNo = $model->getField('no',true);
$arr =array();
while(($row = fgetcsv($fp,1000,",")) !==false){
$row = array_combine($fields,$row); //读取文件中的一条数据
if(in_array($row['no'],$arrNo)){
echo '学号已存在' . '<br>';
}else{
$arr[]=$row;
$arrNo[]=$row['no'];
echo '学号已导入' . '<br>';
}
if(count($arr) == 1000){
$model->addAll($arr);
unset($arr);
}
}
if(count($arr)>0){
$model->addAll($arr);
}
$this->show('添加成功','utf8');
}
}
在实现下载时,程序如下
<?
$file_name = ""; //下载文件名
$file_dir = ""; //下载文件存放目录
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;}
?>