zend framework file upload function example code

  • 2020-12-09 00:47:30
  • OfStack


// Instantiate the upload class 
$upload = new Zend_File_Transfer();
// Set the filter size limit to 5M The format for jpg,gif,png
$upload->addValidator('Size', false, 5 * 1024 * 1024);
$upload->addValidator('Extension', false, 'jpg,gif,png');
if (!$upload->isValid()) {
    print ' The file size or format does not match ';
    exit();
}
// Get the uploaded file form, there can be more than one 
$fileInfo = $upload->getFileInfo();
// Get the suffix name, here pic For upload form file The control of name        
$ext = $this->getExtension($fileInfo['pic']['name']);
// Define the build directory 
$dir = './upload' . date('/Y/m/d/');
// File renaming 
do {
    $filename = date('His') . rand(100000, 999999) . '.' . $ext;
} while (file_exists($dir . $filename));
// Create a directory if it does not exist 
$this->makeDir($dir);
// Formally write the file to the upload directory 
$upload->setDestination($dir);
$upload->addFilter('Rename', array('target' => $filename, 'overwrite' => true));
if (!$upload->receive()) {
    print ' Failed to upload image ';
    exit();
}
print $filename;

How to get the file extension:


/**
 *  Gets the file extension 
 * 
 * @param string $fileName
 * @return string
 */
public function getExtension($fileName) {
    if (!$fileName) {
        return '';
    }
    $exts = explode(".", $fileName);
    $ext = end($exts);
    return $ext;
}

How to create a directory:


/**
 *  Create a directory 
 * 
 * @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;
}


Related articles: