sfw 强悍的附件上传功能 -- 一周从无到有开发一个完整的企业站

 

后端代码:

<?php
/**
 * 附件上传管理
 *
 */
class PQAdmin_AttachmentController extends PQAdmin_BaseController {
	
	function actionNew(){
		
		$allowext = $this->_request_->request('allowext',null);
		$callback = $this->_request_->request('callback',null);
		$label = $this->_request_->request('label',null);
		
		$this->_view['allowext'] = $allowext;
		$this->_view['callback'] = $callback;
		$this->_view['label'] = $label;
		
		$this->_viewname = 'show';
	}
	
	function actionSave(){
		
		$allowext = $this->_request_->request('allowext',App::ini('_uploader/allowext'));
		$callback = $this->_request_->request('callback',null);
		$label = $this->_request_->request('label',null);
		
		$maxSize = App::ini('_uploader/maxsize');
		$uploadDir = App::ini('_uploader/dir');
		$uploadBaseurl = App::ini('_uploader/baseurl');
		
		$prefix = date('Y/m/d',CURRENT_TIMESTAMP);
		
		do {
			if (is_dir($uploadDir) && is_writable($uploadDir)){
				
				$fileDir = $uploadDir . '/' . $prefix;
				if (is_dir($fileDir)){
					
					if (!is_writable($fileDir)){
						js_alert("上传文件目录[{$fileDir}]不可写,请检查权限设置",'',$this->_request_->referer());
					}
		  			
		  		}else {
		  			if (!FileSystemHelper::mkdirs($fileDir)){
		  				js_alert("上传文件目录[{$fileDir}]创建失败,请检查权限设置",'',$this->_request_->referer());
		  			}
		  		}
				
				break;
			}
			js_alert("上传文件目录[{$uploadDir}]不可写,请检查权限设置",'',$this->_request_->referer());
			
		} while(false);
				
		$uploader = new FileUploaderHelper();
		
		$files = $uploader->getFiles();
		
		$fileInfo = array();
		
		// 这个地方每次只会上传一个文件
		foreach ($files as $file) {
		  	if (!$file->check($allowext, $maxSize)) {
				// 上传的文件类型不符或者超过了大小限制。
				js_alert(App::ini('_uploader/errorstext'),'',$this->_request_->referer());
				return false;
			}
			// 生成唯一的文件名(重复的可能性极小)
		  	
		  	$id = md5(time() . $file->getFilename() . $file->getSize() . $file->getTmpName());
		  	$filename = $id . '.' . strtolower($file->getExt());
		  	$file->move($fileDir . '/' . $filename);
		  	
		  	$fileInfo['name'] = "/{$prefix}/{$filename}";
		  	$fileInfo['size'] = $file->getSize();
		  	$fileInfo['mime'] = $file->getMimeType();
		  	
			break;
		}
		
		$this->_view['allowext'] = $allowext;
		$this->_view['callback'] = $callback;
		$this->_view['label'] = $label;
		
		$this->_view['callbackObject'] = json_encode($fileInfo);
		$this->_viewname = 'show';
	}
	
    /**
     * 执行控制器动作之前调用
     */
    protected function _beforeExecute($actionName)
    {
    	// 检查用户是否为登录状态
//    	if (!PQAdmin_UserModel::isLogin()){
//			redirect(url('application','logout'));
//		}
    }
}

 

要使用的地方 只需如此调用即可:

 

<script>

function uploadImg(fileInfo){
	
	console.log(fileInfo);//.uploadImage.value
}
</script>

<div>  	  	
	<iframe src="<?php echo url('attachment','new',null,array('allowext'=>'jpg','callback'=>'window.parent.uploadImg','label'=>h('上传图片:')));?>" style="border:0px;height:30px;width: 100%" frameborder="0" cellspacing="0" allowTransparency="true" scrolling="no" resizable="no"></iframe>
	</div>

 

上传成功会自动执行回调函数:

 

 

输出结果:

{ name="/2011/05/22/03c4524eccb3b33226a83e7817883727.jpg", size=39583, mime="image/jpeg"}

 

贴一个完整的demo:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $_base_dir;?>static/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php echo $_base_dir;?>static/kindeditor/kindeditor-min.js"></script>
<script type="text/javascript">
function changeSelect(qtype){

	document.getElementById('qtype_href').style.display = 'none';
	document.getElementById('qtype_text').style.display = 'none';
	
	switch(parseInt(qtype.value)){		
		case 1:
			document.getElementById('qtype_href').style.display = '';
			break;
		case 2:
			document.getElementById('qtype_text').style.display = '';
			break;
		default:
			break;
	}
	
}

function fnOnSubmit(form) {
	var qtype = document.getElementById('qtype');
	
	form.ctype.value = qtype.value;
	
	switch(parseInt(qtype.value)){		
		case 1:
			form.ctext.value = document.getElementById('qhref').value;
			if (form.ctext.value == ''){
				alert('必须输入栏目地址');
				document.getElementById('qhref').focus();
				return false;
			}
			break;
		case 2:
			form.ctext.value = KE.util.getData('qtext');
			if (form.ctext.value == ''){
				alert('必须输入栏目内容');
				document.getElementById('qtext').focus();
				return false;
			}
			break;
		default:			
			form.ctext.value = '';			
			break;
	}
	return true;
}

KE.show({
	id : 'qtext',
	resizeMode : 1,
	allowPreviewEmoticons : false,
	allowUpload : false,
	items : [
	'fontname', 'fontsize', '|', 'textcolor', 'bgcolor', 'bold', 'italic', 'underline',
	'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
	'insertunorderedlist', '|', 'emoticons', 'image', 'link']
});

function uploadFile(fileInfo){
	var attachments = document.getElementById('attachments');
	var tpl = '<p><a class="attachment" href="' + fileInfo.baseurl + fileInfo.name + '">'
		+ fileInfo.name + '&nbsp;&nbsp;(Mime: ' + fileInfo.mime + ')</a></p>'	
	attachments.innerHTML += tpl;
}
</script>
</head>
<body>
<div id="content">
  <h3><?php echo h(sprintf('设置栏目 [%s] 的详情数据', $class['name'])); ?></h3>
  
    <p>选择内容类型:
      <?php 
      
      $this->_control('dropdownlist', 'qtype', 
      	array(
      		'items' => array('空'=>0,'URL链接'=>1,'文本数据'=>2),
      		'selected' => $class['ctype'],
      		'onChange' => 'changeSelect(this)'
      	)
      ); 
      ?>
    </p>
  	<p id="qtype_href" style="<?php echo $class['ctype'] != 1 ? 'display: none' : '';?>">输入栏目地址:
  	<?php $this->_control('textbox', 'qhref', array('value' => $class['ctext'],'size' => 40,)); ?>
  	</p> 
  	<p id="qtype_text" style="<?php echo $class['ctype'] != 2 ? 'display: none' : '';?>">输入栏目内容:<br/>
  	<?php $this->_control('memo', 'qtext', array('value' => $class['ctext'],'style'=>"width:650px;height:300px;visibility:hidden;")); ?>
  	<br/>
  	<div id="attachments"></div> 
  	<iframe src="<?php echo url('attachment','new',null,array('allowext'=>'jpg|png|gif|bmp|rar|zip|pdf','callback'=>'window.parent.uploadFile','label'=>h('上传新文件:')));?>" style="border:0px;height:30px;width: 100%" frameborder="0" cellspacing="0" allowTransparency="true" scrolling="no" resizable="no"></iframe>
  	
  	</p> 
  <form id="form1" name="form1" method="post" action="<?php echo url('zhsysmodule','saveMetadata');?>" onsubmit="return fnOnSubmit(this);">
    <p>  
    <?php $this->_control('hidden', 'id',array('value'=>$class['id'])); ?>
    <?php $this->_control('hidden', 'ctype'); ?>
    <?php $this->_control('hidden', 'ctext'); ?>
      <input name="Save" type="submit" id="Save" value="<?php echo h(' 提 交 '); ?>" />
      &nbsp;&nbsp;
    <input name="Cancel" type="button" id="Cancel" value="<?php echo h(' 取 消 '); ?>" onclick="document.location.href = '<?php echo $backurl; ?>';"/>
    </p>
  </form>
</div>
</body>
</html>
 

截图如下:

 


sfw 强悍的附件上传功能 -- 一周从无到有开发一个完整的企业站