Home >php教程 >php手册 >zend framework文件上传功能实例代码

zend framework文件上传功能实例代码

WBOY
WBOYOriginal
2016-06-06 20:26:001082browse

zend framework文件上传功能实例代码,php的版本5.3.8,zend framework的版本1.12,看下面的代码吧,有注释

复制代码 代码如下:


//实例化上传类
$upload = new Zend_File_Transfer();
//设置过滤器,,大小限制为5M,格式为jpg,gif,png
$upload->addValidator('Size', false, 5 * 1024 * 1024);
$upload->addValidator('Extension', false, 'jpg,gif,png');
if (!$upload->isValid()) {
    print '文件大小或格式不符合';
    exit();
}

//获取上传的文件表单,可以有多项
$fileInfo = $upload->getFileInfo();
//获取后缀名,这里pic为上传表单file控件的name       
$ext = $this->getExtension($fileInfo['pic']['name']);
//定义生成目录
$dir = './upload' . date('/Y/m/d/');
//文件重新命名
do {
    $filename = date('His') . rand(100000, 999999) . '.' . $ext;
} while (file_exists($dir . $filename));

//如果目录不存在则创建目录
$this->makeDir($dir);
//将文件正式写入上传目录
$upload->setDestination($dir);
$upload->addFilter('Rename', array('target' => $filename, 'overwrite' => true));
if (!$upload->receive()) {
    print '上传图片失败';
    exit();
}

print $filename;

获取文件扩展名的方法:

复制代码 代码如下:


/**
 * 获取文件扩展名
 *
 * @param string $fileName
 * @return string
 */
public function getExtension($fileName) {
    if (!$fileName) {
        return '';
    }
    $exts = explode(".", $fileName);
    $ext = end($exts);
    return $ext;
}

创建目录的方法:

复制代码 代码如下:


/**
 * 创建目录
 *
 * @param string $path
 * @return boolean
 */
public function makeDir($path) {
    if (DIRECTORY_SEPARATOR == "\\") {//windows os
        $path = iconv('utf-8', 'gbk', $path);
    }
    if (!$path) {
        return false;
    }
    if (file_exists($path)) {
        return true;
    }
    if (mkdir($path, 0777, true)) {
        return true;
    }
    return false;
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn