日期:2014-05-17  浏览次数:20487 次

ThinkPHP学习笔记(十四)上传文件

需要进行Action的设置,包括UploadFile的文件引入

<?php
/**
 * 处理文件上传功能
 * @author admin
 *
 *	上传多文件时;
 *	可以在input中个的name中后加入[];例如:file[]
 *	或者可以设置标示:file1,file2
 *
 *	只有在插入数据库的时候才需要进行循环插入
 */
class FileAction extends Action{
	public function index(){
		$file=M('file');
		$list=$file->select();
		$this->assign('alist',$list);
		$this->display();
	}
	function upload(){
		//经过自定义模型
		if (empty($_FILES)){
			$this->error("必须选择上传文件");
		}else {
			$msg = $this->up();
			if (isset($msg)){
				$result=$this->insertDb($msg);
				if ($result){
					$this->success('上传成功');
				}else{
					$this->error('保存出错了那');
				}
			}else{
				$this->error($msg);
			}
		}
	}
	
	private function insertDb($data){
		$file=M('file');
		$result=true;
		for ($i = 0; $i < count($data); $i++) {
			$data['filename']=$data[$i]['savename'];
			if (!$file->data($data)->add()){
				return false;
			}
		}
		return true;
	}
	
	private function up(){
		import('ORG.Net.UploadFile');
		$upload=new UploadFile();
		$upload->maxSize='1000000';//大小:-1不限制;单位是bytes
		$upload->savePath='./Public/';//上传路径:建议以主路口或者平级目录的子目录来
		$upload->saveRule='uniqid';//保存规则:默认是uniqid
		$upload->hashType='MD5';//hash验证方法,默认是md5
		$upload->autoCheck=false;
		$upload->uploadReplace=true;
		$upload->allowExts=array('jpg','png');//允许上传的文件格式
		$upload->allowTypes=array('image/png','image/jpg');//文件的mime类型
		
		$upload->thumb=true;//是否开启图片文件缩略图
		$upload->thumbMaxWidth='100,500';//可以用,分割,写多个最大宽度
		$upload->thumbMaxHeight='100,500';//与width一一对应
		$upload->thumbPrefix='s_,m_';//缩略图文件前缀,与width一一对应
//		$upload->thumbPath='';//缩略图的保存路径,如果为空直接上传至$upload->savePath
//		$upload->thumbFile='';//缩略图的文件名,一般不会用,直接用前缀就可以了
		$upload->thumbRemoveOrigin=1;//生成新图后是否删除原图
		
//		$upload->autoSub=false;//是否使用子目录进行保存
//		$upload->subType='';//子目录创建方式,默认为hash创建,也可以设置为date
//		$upload->dateFormat='';//子目录date方式的指定格式
//		$upload->hashLevel='';//hash的层级

		
		if ($upload->upload()) {
			$msg=$upload->getUploadFileInfo();
			dump($msg);
			return $msg;
		}else {
			$this->error($upload->getErrorMsg());
			return $upload->getErrorMsg();
		}
		
	}
}
?>

html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><!--{$title}--></title>
</head>
<body>
<volist name="alist" id="vo">
	<img src="__PUBLIC__/s_<!--{$vo['filename']}-->"/>
	<img src="__PUBLIC__/m_<!--{$vo['filename']}-->"/>
</volist>
<form action="__URL__/upload" method="post" enctype="multipart/form-data">
	<input type="file" name="file[]">
	<input type="file" name="file[]">
	<input type="submit" value="提交">
</form>
</body>
</html>