Zend framework file upload function instance code

Source: Internet
Author: User

Copy codeThe 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:

Copy codeThe 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:

Copy codeThe 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.