封裝原生的檔案上傳類
阿新 • • 發佈:2019-01-22
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title></title> </head> <body> <form method="post" action="rikao_info.php" enctype="multipart/form-data"> <input type="file" name="filename"> <input type="submit" value="上傳"> </form> </body> </html>
封裝的上傳類
php後臺處理<?php header('connect-type:text/html;charset=utf-8'); /*檔案上傳類*/ class Upload{ /*@param string 上傳引數*/ public function up($file){ /*獲取檔案引數 param array $file 接受檔名引數 */ $filename = isset($file['name'])?$file['name']:''; $filetype = isset($file['type'])?$file['type']:''; $filesize = isset($file['size'])?$file['size']:''; $fileerror = isset($file['error'])?$file['error']:''; $filetmp = isset($file['tmp_name'])?$file['tmp_name']:''; /* 判斷檔案大小*/ if($filesize > 1024*1024*2){ echo "檔案過大";die(); } /*判斷檔案型別*/ $type = array('image/jpg','image/gif','image/png','image/jpeg'); if(!in_array($filetype,$type)){ echo "檔案格式錯誤";die(); } /*判斷檔案錯誤程式碼 */ switch ($fileerror) { case 1: echo '上傳的檔案超過了 php.ini 中 upload_max_filesize 選項限制的值!'; break; case 2: echo '上傳檔案的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值!'; break; case 3: echo '檔案只有部分被上傳!'; break; case 4: echo '沒有檔案被上傳!'; break; case 6: echo '找不到臨時資料夾!'; break; case 7: echo '檔案寫入失敗!'; break; } /*判斷檔案目錄 param string $path 檔案目錄路徑*/ $path = './Uploads/'.date('Y').'/'.date('m').'/'.date('d').'/'; //file_exists 一個引數 判斷檔案是否存在 //is_dir 一個引數 檢測路徑是否存在 if(!file_exists($path)){ if(!mkdir($path,0777,true)){ echo "檔案目錄建立失敗";die(); } } /*移動檔案:將臨時檔案移動到指定檔案當中*/ $new_name = time().rand(0,999999999).substr($filename,strrpos($filename,'.')); if(move_uploaded_file($filetmp,$path.$new_name)){ return $path.$new_name; }else{ return false; } } } ?>
<?php header('content-type:text/html;charset=utf8'); //include('./Smarty/Smarty.class.php'); include('./DB.class.php'); include('./Upload.class.php'); $uploads=new Upload; $filename=isset($_FILES['filename'])?$_FILES['filename']:''; $_POST['filename']=$uploads->up($filename); $db=new Db; $res=$db->Add('pictures',$_POST); if($res){ echo "新增成功"; header('location:show.php'); }else{ echo "新增成功"; } ?>