CodeIgniter HMVC是一个基于CodeIgniter框架的扩展,它允许开发者将应用程序划分为模块化的组件,以便更好地组织和管理代码。在使用CodeIgniter HMVC上传文件时,可以按照以下步骤进行操作:
application/config/config.php
文件,找到以下配置项并进行相应修改:$config['base_url'] = 'http://your-domain.com'; // 设置应用程序的基本URL
$config['index_page'] = ''; // 如果使用URL重写,可以将此项设置为空
$config['encryption_key'] = 'your-encryption-key'; // 设置加密密钥,用于加密上传的文件名
// 设置上传文件的保存路径
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png'; // 允许上传的文件类型
$config['max_size'] = 2048; // 允许上传的最大文件大小(单位:KB)
$config['max_width'] = 0; // 允许上传的最大图片宽度(0表示不限制)
$config['max_height'] = 0; // 允许上传的最大图片高度(0表示不限制)
application/controllers/
目录,创建一个新的控制器文件(例如Upload.php
),并添加以下代码:<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['encrypt_name'] = TRUE; // 使用加密文件名
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
application/views/
目录下创建两个文件,分别命名为upload_form.php
和upload_success.php
,并添加以下代码:upload_form.php:
<html>
<head>
<title>文件上传</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="上传" />
</form>
</body>
</html>
upload_success.php:
<html>
<head>
<title>文件上传成功</title>
</head>
<body>
<h3>文件上传成功!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', '再次上传文件'); ?></p>
</body>
</html>
application/config/routes.php
文件,添加以下路由规则,以便访问上传功能:$route['upload'] = 'upload';
$route['upload/do_upload'] = 'upload/do_upload';
uploads
文件夹具有写入权限。然后,在浏览器中访问http://your-domain.com/upload
,即可看到文件上传表单。领取专属 10元无门槛券
手把手带您无忧上云