<?php session_start();header("Content-type: text/html; charset=utf-8"); include_once 'Upload.class.php';upload::setVerifyBySession();if($_POST["sbt"]){ $upload = new upload("pic", $_POST["verify"]); $picName = $upload->uploadFile();}?><html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <head> <title>多檔案上傳</title> </head> <body> <a href="#" onclick="add()">增加圖片上傳窗</a><form action="" method="post" enctype="multipart/form-data" onSubmit="return btn();"><div id="inputArea"> <input type="file" name="pic[]" /></div><input type="submit" name="sbt" value="上傳" /><input type="hidden" name="verify" value='<?php echo $_SESSION["verify"] ?>' /></form><script type="text/javascript"> function btn() { var flag = false; var objs = document.getElementsByName("pic[]"); for(var i=0; i < objs.length; i++) { var obj = objs[i]; if(obj.value != "") { flag = true; } } return flag; } function add() { var input = document.getElementById("inputArea"); input.innerHTML += "<br /><input type=\"file\" name=\"pic[]\" />"; }</script></body> </html>
Upload.class.php
<?php/** * 圖片上傳類 */class upload{ private $verify; //用於方式重新整理導致重複上傳的比較參數 private $dir; //上傳目錄 private $img; //上傳的圖片資訊 public function __construct($inputName, $verify) { session_start(); $this->img = $_FILES[$inputName]; $this->verify = $verify; $this->dir = dirname(__FILE__) . "\uploads"; } /** * 設定防止重複重新整理提交的比較參數Verify */ public static function setVerifyBySession() { if(!isset($_SESSION["verify"])) { $_SESSION["verify"] = time(); } } /** * 上傳圖片主邏輯 */ public function uploadFile() { self::repeatSubmit(); self::directoryExist(); $i = 0; foreach ($this->img["tmp_name"] as $tmp) { $filename = explode(".", $this->img["name"][$i++]); $filename = self::setName($filename); if($tmp) { $savepath = $this->dir . "\\" . $filename; $stats = move_uploaded_file($tmp, $savepath); self::showPic($stats, $filename); } } } /** * 判斷是否重複提交 */ private function repeatSubmit() { if($this->verify != $_SESSION["verify"]) { echo "<script>alert('請勿重複提交!'); window.location.href = './'</script>"; exit(); } else { unset($_SESSION["verify"]); } } /** * 判斷上傳目錄是否存在 */ private function directoryExist() { if(!file_exists($this->dir)) { mkdir($this->dir); } } /** * 給上傳檔案重新命名 */ private function setName($f) { $name = md5($f[0] . date("mdHis") . rand(1, time())); return $name . "." . $f[1]; } /** * 上傳成功後,顯示上傳圖片 */ private function showPic($stats, $filename) { if($stats) { echo "<img src = 'uploads/$filename' />" . $filename . "<br>"; } }}?>