Zend Framework 2 入门 文件上传

本文简要介绍ZF2的文件上传。

首先我们来做一个最简单的文件上传:
Step:1
建立一个新模块Upload
目录结构如下:

/module
    /Upload
        /config
            module.cong.php
        /src
            /Upload
                /Controller
                    IndexController.php
        /view
            /upload
                /index
                    index.phtml
        Module.php

关于module.cong.php、 Module.php文件以及application.cong.php的配置这里就不多说了,详情见以前的文章。

Step 2:
index.phtml文件<>

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="fileupload" /"> 
    <input type="submit" value="提交" /">
</form >

Step 3:
IndexController.php文件

<?php
/** 
 * 图片服务器视图助手 
 * 
 * @author Star <wmistar@gmail.com> 
 * @license http://mushroot.com 
 * @version: 1.0 
 */
namespace Upload\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\File\Transfer\Adapter\Http;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        if ($this->getRequest()->isPost()) {
            $files = $this->getRequest()->getFiles();
            $file  = $files->fileupload;

            $fileAdapter = new Http();

            //重新生成文件名
            $newName = $this->oldName($file['name']);

            //储存文件
            $fileAdapter->addFilter('File\Rename',
                array('target'    => '/var/www/html/zftest/public/img/'.$newName,
                      'overwrite' => true,
                      'source'    => $file['tmp_name'],
                ));

            if ($fileAdapter->receive($file['name']))
                $resFile = $fileAdapter->getFilter('File\Rename')->getFile();

            print_r($resFile);
            exit();
        }
        return new ViewModel();
    }

    public function oldName($oldName)
    {
        $oldType = substr($oldName,strrpos($oldName,"."));
        $this->type = $oldType;
        $newName = time().floor(microtime() * 10000).rand(10, 99);

        return $newName.$oldType;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值