Zendframework file upload function instance code, php version 5.3.8, zendframework version 1.12, see the following code, there are annotations
The code is as follows:
// Instantiate the upload class
$ Upload = new Zend_File_Transfer ();
// Set the filter size to 5 MB. the format is jpg, gif, and png.
$ Upload-> addValidator ('size', false, 5*1024*1024 );
$ Upload-> addValidator ('extension', false, 'jpg, gif, png ');
If (! $ Upload-> isValid ()){
Print 'file size or format mismatch ';
Exit ();
}
// Obtain the uploaded file form, which can contain multiple
$ FileInfo = $ upload-> getFileInfo ();
// Get the suffix. here, pic is the name of the file control in the upload form.
$ Ext = $ this-> getExtension ($ fileInfo ['Pic '] ['name']);
// Define the generated Directory
$ Dir = './upload'. date ('/Y/m/d /');
// Rename the file
Do {
$ Filename = date ('his '). rand (100000,999 999).'. '. $ ext;
} While (file_exists ($ dir. $ filename ));
// Create a directory if the directory does not exist
$ This-> makeDir ($ dir );
// Write the file to the upload Directory
$ Upload-> setDestination ($ dir );
$ Upload-> addFilter ('rename', array ('target' => $ filename, 'overwrite' => true ));
If (! $ Upload-> receive ()){
Print 'image Upload failed ';
Exit ();
}
Print $ filename;
How to get the file extension:
The code is as follows:
/**
* Get 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:
The code is as follows:
/**
* 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;
}