HTML的form表單
用html的表單模擬一個文件上傳的post請求,代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>File Upload</title> </head> <body> <form enctype="multipart/form-data" action="test.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> Send this File:<input name="userfile" type="file"/> <input type="submit" value="Send File" /> </form> </body> </html>
注意:
要確保文件上傳表單的屬性是 enctype="multipart/form-data",否則文件上傳不了
PHP
首先,需要解釋一下PHP的全局變量$_FILES,此數組包含了所有上傳的文件信息
思路
1、生成40位的隨機字符串作為文件名
2、根據文件是圖片還是語音轉存到不同的文件位置
3、暫時不做文件大小和文件類型的校驗
function processFile($files, $type) { $uploadName = null; foreach ($files as $name => $value) { $originalName = $value['name']; $arr = explode(".", $originalName); $postfix = $arr[count($arr) - 1]; $tmpPath = $value['tmp_name']; $tmpType = $value['type']; $tmpSize = $value['size']; } $newname = EhlStaticFunction::generateRandomStr(40).".".$postfix; switch ($type) { case 1 : // 處理聲音文件 $destination = VIDEOUPLOADDIR.$newname; break; case 2 : // 處理圖像文件 $destination = IMAGEUPLOADDIR.$newname; break; } move_uploaded_file($tmpPath, $destination); }
而獲取所上傳文件的後綴名則可以使用一下代碼:
HTML
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta name="keywords" content=" keywords" /> <meta name="description" content="description" /> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="upfile" size="20" /> <input type="submit" name="submit" value="submit" /> </form> </body> </html>
PHP
<?PHP if(isset($_POST['submit'])) { $string = strrev($_FILES['upfile']['name']); $array = explode('.',$string); echo $array[0]; } ?>
結果示例: