ThinkPHP导入文件并上传与文件下载

在做网站项目时必不可少就是导入文件将数据传进数据表中,并将插入数据写入日志文件并下载。下面是我的代码与心得。

第一步:给表单中的input添加一个name属性为file,action设置为当前控制器下的upload方法,特别注意:一定要在表单中写入enctype="multipart/form-data

<form role="form" method="post" action="__URL__/upload" enctype="multipart/form-data">
	<div class="modal-body">
		<div class="form-group">
			<input type="file" id="inputfile" name="file">
		</div>
	</div>
	<div class="modal-footer">
		<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		<button type="submit" class="btn btn-primary">导入</button>
	</div>
</form>

第二步:在当前控制器下新建upload方法,先判断是否为post方式提交,如果不是则退出;设置上传文件的属性如大小、后缀、根目录等,调用Think模块的Upload方法,上传文件,失败则提示。最后调用import方法,并将文件路径作为参数传递过去。

public function upload(){
	if(IS_GET){
		$this->display();
		exit;
	}
	$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('上传成功!' . $info['file']['savepath'] . $info['file']['savename']);
		$file = './Public/upload/' . $info['file']['savepath'] . $info['file']['savename'];//文件的完整路径
		$this->import($file);//调用import方法
	}
}

第三步:先检测文件编码是否为utf8格式(检测编码格式的函数将在下文展示),因为学号为主键不能重复,所以要检测导入文件中的学号是否已经存在,要将数据表中的学号提出来放到一个数组中,再将文件里的学号插入到数组中,无论是否存在都将信息写入到日志文件中,并下载。

public function import($file){
    //检测文件编码
    $encoding=detect_encoding($file);
    //如果不是utf8格式,则转化为utf8
    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);
			// dump($arrno);
			// exit;
			$arr=array();
            $file = 'log.txt';
			$file = fopen($file, 'w');
			while(($row=fgetcsv($fp,1000,","))!==false){
				$row=array_combine($fields, $row);
				if(in_array($row['no'],$arrno)){
				  $content = $row['no'] . "已存在" . PHP_EOL;
				}else{
                   $arrno[] = $row['no'];
                   $name = $row['name'];
                   $py = SpGetPinyin($name);
					   $row['py'] = $py;
					   $password = '123456';
					   $row['password'] = md5($password);
					   $create_time = intval(time());
					   $row['create_time'] = $create_time;
                   $arr[] = $row;
                   $content = $row['no'] . "导入成功" .PHP_EOL;
				}
                fwrite($file, $content);
				// dump($row);
				if(count($arr) == 1000){
					$model->addAll($arr);
					unset($arr);
				}
			}
			fclose($file);
			if(count($arr)>0){
				$model->addAll($arr);
			}
			// $this->success('添加成功');
			$this->download();
		}
}
第五步:先定义要下载的文件名称和存放目录,使用file_exists()函数检测文件是否存在,使用header设置各种属性用来显示都爱浏览器中即可完成
// 文件下载
protected function download(){
	$file_name = "log.txt";     //下载文件名    
	$file_dir = ROOT . "/";   //下载文件存放目录  
	echo $file_dir . $file_name;
	//检查文件是否存在    
	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 ();    
	}     
}

效果:

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值