Multifile upload and Modification

Source: Internet
Author: User
Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn. if you write a file upload class to upload multiple files, you can only get one file name, because the original file name is stored with string member variables, only one can be saved. This side changes the variable storing the file name to an array. After uploading, the user obtains an array, contains all uploaded files
/**
* FileUpload. class. php
* @ Description multi-File Upload class
* @ Author: yulipu
* Time: 2013-10-3
* Include "FileUpload. class. php ";
* $ Up = new FileUpload (array ('savepath' => './mytest /'));
* $ Up-> uploadFile ('userfile'); // when userfile is the name value of the input box and multiple files, the name value of the input must contain brackets: name = "userfile []" no brackets can only upload the first file
* Echo $ up-> getErrorMsg (); // get the error message.
*
* All basic functions are passed in the constructor as parameters.
* Specify the Upload File Format [array] allowtype
* Specify the file size [int] maxsize
*
* Instance 1 uploads the Avatar to the specified directory and saves the name immediately. The file name length is 20 (20 by default)
* $ Up = new FileUpload (array ('savepath' => './avatar/', 'israndname' => true, 'newfilenamelength '=> 20 ));
* Instance 2 uploads an avatar to a specified directory and uses the user ID as the file name. For example, upload photo.png and save it as 2.png.
* $ Up = new FileUpload (array ('savepath' => './avatar/', 'israndname' => false, 'givenfilename '=> 2 ));
* Instance 3 upload an avatar to a specified directory. Create a subdirectory in the directory by date to save the Avatar.
* $ Up = new FileUpload (array ('savepath' => '. /avatar/', 'subdirpattern' => 'y/m', 'israndname' => false, 'givenfilename '=> 2 ));
* The generated directory is './avatar/123'
*/
Class FileUpload {
Private $ name = 'name ';
Private $ type = 'type ';
Private $ tmp_name = 'tmp _ name ';
Private $ error = 'error ';
Private $ size = 'SIZE ';

// Fields used by the constructor
Private $ savepath = ''; // specifies the path to save the uploaded file
Private $ subdirpattern = ''; // if the value is null in combination with savepath, no sub-directories are added. If the value is null, for example, 'y/m' indicates 2011/01, the SAVE path is $ savepath. '/123'
Private $ allowtype = array ('gif', 'jpg ', 'png ');
Private $ maxsize = 204800; // Byte 200 K
Private $ israndname = true; // whether to rename the file randomly. true. false. The original file name is not used randomly.
Private $ givenfilename = ''; // use the given file name with israndname
Private $ ignoreemptyfile = true; // whether to ignore text fields that do not upload files
Private $ newfilenamelength = 20;

// Fields used in this class
Private $ errorMessage = '';
Private $ uploadFileArray = null;
Private $ originalFileName = '';
Private $ expandedName = '';
Public $ newFileName = array ();


// 1. Specify the upload path, 2, the acceptable type, 3, size limit, 4, whether to use the random file name
// New FileUpload (array ('savepath' => '. /uploads/', 'allowtype' => array ('txt', 'gif'), 'israndname' => true ));
Public function _ construct ($ args = array ()){
Foreach ($ args as $ key => $ value ){
$ Key = strtolower ($ key );
// Check whether the subscript of the array in the USER parameter is the same as the member attribute name
// If (! In_array ($ key, get_class_vars (get_class ($ this )))){
// Continue;
//}
$ This-> setArgs ($ key, $ value );
}
}

Private function setArgs ($ key, $ value ){
$ This-> $ key = $ value;
}

/**
* Get the file size.
* @ Param int size Byte Count
*/
Private function getFileSize ($ size ){
$ Unit = 'bytes ';
If ($ size <1024 ){
Return $ size. $ unit;
} Else if ($ size <pow (1024, 2 )){
$ Unit = 'kb ';
$ Size = round ($ size/1024, 2 );
} Else if ($ size <POWs (1024, 3 )){
$ Unit = 'mb ';
$ Size = round ($ size/pow (1024, 2), 2 );
} Else if ($ size <pow (1024, 4 )){
$ Unit = 'gb ';
$ Size = round ($ size/pow (1024, 3), 2 );
} Else {
$ Unit = 'tb ';
$ Size = round ($ size/pow (1024, 4), 2 );
}

Return $ size. $ unit;
}

/**
* Obtain an array consisting of keys of an array.
*/
Private function myArray_keys (& $ arr ){
$ ReturnArr = array ();
Foreach ($ arr as $ key => $ val ){
$ ReturnArr [] = $ key;
}

Return $ returnArr;
}
/* No sorting
Array
(
[F1] => Array
(
[Name] => Array
(
[0] => Winter.jpg
)
// If [] is added, the name format is an array. Only multi-file is supported.
// If no [] is added, the name format is a string, that is, only the first file can be uploaded.

[Type] => Array
(
[0] => image/jpeg
)

[Tmp_name] => Array
(
[0] => C: \ WINDOWS \ TEMP \ phmongod. tmp
)

[Error] => Array
(
[0] => 0
)

[Size] => Array
(
[0] = & gt; 105542
)

)

)
*/

/**
* Rearrange the uploaded files
* $ UploadFileArray array of objects uploaded
*/
Private function reSortFile (& $ uploadFileArray ){
// If the input name does not contain [], it is a string.
// If [] exists, it is an array.
$ MultiFlag = is_array ($ uploadFileArray [$ this-> name])? True: false;
$ File_arr = array ();

$ File_num = $ multiFlag? Count ($ uploadFileArray [$ this-> name]): 1; // calculates the number of uploaded files.
$ File_keys = $ this-> myArray_keys ($ uploadFileArray); // obtain the array, including name type error tmp_name size

For ($ I = 0; $ I <$ file_num; $ I ++ ){
Foreach ($ file_keys as $ value ){
$ File_arr [$ I] [$ value] = $ multiFlag? $ UploadFileArray [$ value] [$ I]: $ uploadFileArray [$ value];
}
}

Return $ file_arr;
}

/**
* Error Report
* $ Error no
*/
Private function setErrorMsg ($ errorno ){
$ Msg = "error when uploading file {$ this-> originalFileName :";
Switch ($ errorno ){
Case 1:
Case 2:
$ Msg. = 'the file is too large to be uploaded'; // the size of the configuration file
Case 3:
$ Msg. = 'file only partially upload'; break;
Case-1:
$ Msg. = 'non-sufficient file type'; break;
Case-2:
$ Msg. = 'the file is too large and cannot exceed'. $ this-> getFileSize ($ this-> maxsize); break;
Case-3:
$ Msg. = 'upload failed'; break;
Case-4:
$ Msg. = 'failed to create a directory to store the uploaded files. Please specify the upload directory again '; break;
Case-5:
$ Msg. = 'file upload path must be specified '; break;
Case-6:
$ Msg. = 'file not uploaded '; break;
Default: $ msg. = "Unknown error ";
}
Return $ msg .'
';
}

/**
* Check whether the upload path is specified.
*/
Private function emptySavePath (){
If (empty ($ this-> savepath )){
$ This-> errorMessage. = $ this-> setErrorMsg (-5 );
Return true;
}
Return false;
}

/**
* Get the extension.
* $ FileName file name
*/
Private function getExpandedName (){
$ Pos = strrpos ($ this-> originalFileName ,'.');
Return substr ($ this-> originalFileName, $ pos + 1 );
}

/**
* Check whether the file extension is valid.
*/
Private function isLegalExpandedName (){
If (in_array ($ this-> expandedName, $ this-> allowtype )){
Return true;
}
$ This-> errorMessage. = $ this-> setErrorMsg (-1 );

Return false;
}

/**
* Check whether the uploaded file is correct.
* $ I files
*/
Private function hasError ($ I ){
$ Errorno = $ this-> uploadFileArray [$ I] [$ this-> error];
If (0 = $ errorno ){
Return 0; // The file is normal.
} Else if (4 ==$ errorno ){
Return 4; // No file is uploaded
}
$ This-> errorMessage. = $ this-> setErrorMsg ($ errorno );

Return 99; // file Error
}

/**
* Check the file size.
* $ I files
*/
Private function isLegalSize ($ I ){
$ FileSize = $ this-> uploadFileArray [$ I] [$ this-> size];
If ($ fileSize <= $ this-> maxsize ){
Return true;
}
$ This-> errorMessage. = $ this-> setErrorMsg (-2 );
Return false;
}

/**
* Check whether the file is uploaded through http post.
* $ I files
*/
Private function isUploadedFile ($ I ){
$ TmpName = $ this-> uploadFileArray [$ I] [$ this-> tmp_name];
If (is_uploaded_file ($ tmpName )){
Return true;
}
$ This-> errorMessage. = $ this-> setErrorMsg (-6 );
Return false;
}

/**
* Get the new file name (the old file name is used if the user specifies not to use the new file name)
*
*/
Private function initNewFileName (){
$ Str = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy ';
$ Chars = $ this-> originalFileName; // With a suffix. jpg
If ($ this-> israndname ){
$ Chars = '';
For ($ I = 0; $ I <$ this-> newfilenamelength-8; $ I ++ ){
$ Chars. = substr ($ str, mt_rand (0, strlen ($ str)-1), 1 );
}
$ Chars. = date ('ymd', time ());
$ Chars = $ chars. '.'. $ this-> expandedName;
} Else {
// The specified name is specified.
If (''! = $ This-> givenfilename ){
$ Chars = $ this-> givenfilename. '.'. $ this-> expandedName;
}
}

Return $ chars;
}

/**
* Copy an object to a specified location
* $ I files
*/
Private function copyFile ($ I ){
$ This-> newFileName [$ I] = $ this-> initNewFileName ();

If (is_dir ($ this-> savepath )){
@ Move_uploaded_file ($ this-> uploadFileArray [$ I] [$ this-> tmp_name], $ this-> savepath. $ this-> newFileName [$ I]);
} Else {
Die ('upload Directory Creation failed ');
}
}

/**
* Check for empty files
*/
Private function chkEmptyFile (& $ arr ){
$ Flag = 1;
For ($ I = 0; $ I <count ($ arr); $ I ++ ){
If (intval ($ arr [$ I] [$ this-> error]) = 4 ){
$ Flag = 4;
Break;
}
}

Return $ flag;
}

/**
* Initialize the upload folder.
*/
Private function initSavePath (){
$ This-> savepath = rtrim ($ this-> savepath ,'/').'/';
! Empty ($ this-> subdirpattern) & $ this-> savepath = $ this-> savepath. date ($ this-> subdirpattern, time ()).'/';

$ TmpSavePath = rtrim ($ this-> savepath ,'/');
If (! Is_dir ($ tmpSavePath )){
$ Dirs = explode ('/', $ tmpSavePath );
$ RealDir = '';
For ($ I = 0; $ I <count ($ dirs); $ I ++ ){
If ($ dirs [$ I] = '') continue;
If ($ dirs [$ I] = '.'){
$ RealDir. = './';
} Else {
$ RealDir = $ realDir. $ dirs [$ I]. '/';
}

If (! Is_dir ($ realDir ))
Mkdir ($ realDir );
}
}
}

/**
* Method for starting File Upload
*/
Private function startUpload (){
For ($ I = 0; $ I UploadFileArray); $ I ++ ){
If (0 ===$ this-> hasError ($ I )){
$ This-> originalFileName = $ this-> uploadFileArray [$ I] [$ this-> name]; // aa.jpg
$ This-> expandedName = $ this-> getExpandedName ();
If ($ this-> isLegalExpandedName ()){
If ($ this-> isLegalSize ($ I )){
// If ($ this-> isUploadedFile ($ I )){
$ This-> copyFile ($ I );
//}
}
}
}
}
}

/**
* File Upload Portal
* $ Name attribute value of the fileField input box
*/
Public function uploadFile ($ fileField ){
// Check the upload path
If (true ===$ this-> emptySavePath ()){
Return false;
}

If (0! = Count ($ _ FILES )){
// Rearrange the uploaded files
$ This-> uploadFileArray = $ this-> reSortFile ($ _ FILES [$ fileField]);

// Start uploading files
If (! $ This-> ignoreemptyfile & 4 ==$ this-> chkEmptyFile ($ this-> uploadFileArray )){
Die ('Force all upload ');

} Else {
$ This-> initSavePath (); // initialize the upload path
$ This-> startUpload ();
}
}
}

/**
* De to error message
*/
Public function getErrorMsg (){
Return $ this-> errorMessage;
}

Public function getUploadFileName (){
Foreach ($ this-> newFileName as $ key => $ val ){
$ This-> newFileName [$ key] = $ this-> savepath. $ this-> newFileName [$ key];
}
Return $ this-> newFileName;
}
}

?>

FileUpload.rar (3.89 KB download: 205 times)

AD: truly free, domain name + VM + enterprise mailbox = 0 RMB

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.