- PHP從入門到精通(第4版)(軟件開發(fā)視頻大講堂)
- 明日科技
- 434字
- 2020-11-28 17:36:40
7.13 綜合運(yùn)用數(shù)組函數(shù)實(shí)現(xiàn)多文件上傳
【例7.16】本例綜合運(yùn)用數(shù)組函數(shù),實(shí)現(xiàn)同時(shí)將任意多個(gè)文件上傳到服務(wù)器的功能。這里文件的上傳使用的是move_uploaded_file()函數(shù),使用array_push()函數(shù)向數(shù)組中添加元素,使用array_unique()函數(shù)刪除數(shù)組中的重復(fù)元素,使用array_pop()函數(shù)獲取數(shù)組中最后一個(gè)元素,并將數(shù)組長度減1,使用count()函數(shù)獲取數(shù)組的元素個(gè)數(shù)。實(shí)例代碼如下:(實(shí)例位置:光盤\TM\sl\7\16)
首先,在index.php文件中創(chuàng)建表單,指定使用post方法提交數(shù)據(jù),設(shè)置enctype="multipart/form-data"屬性,添加表單元素,完成文件的提交操作。
<form action="index_ok.php" method="post" enctype="multipart/form-data" name="form1"> <tr> <td width="88" height="30" align="right" class="STYLE1">內(nèi)容1:</td> <td width="369"><input name="picture[]" type="file" id="picture[]" size="30"></td> </tr> …//省略了部分代碼 <tr> <td height="30" align="right" class="STYLE1">內(nèi)容5:</td> <td><input name="picture[]" type="file" id="picture[]" size="30"></td> </tr> <tr> <td><input type="image" name="imageField" src="images/02-03 (3).jpg"></td> </tr> </form>
然后,在index_ok.php文件中,通過$_FILES預(yù)定義變量獲取表單提交的數(shù)據(jù),通過數(shù)組函數(shù)完成對上傳文件元素的計(jì)算,最后使用move_uploaded_file()函數(shù)將上傳文件添加到服務(wù)器指定文件夾下。
<?php if(! is_dir("./upfile")){ //判斷服務(wù)器中是否存在指定文件夾 mkdir("./upfile"); //如果不存在,則創(chuàng)建文件夾 } $array=array_unique($_FILES["picture"]["name"]); //刪除數(shù)組中重復(fù)的值 foreach($array as$k=>$v){ //根據(jù)元素個(gè)數(shù)執(zhí)行foreach循環(huán) $path="upfile/".$v; //定義上傳文件存儲位置 if($v){ //判斷上傳文件是否為空 if(move_uploaded_file($_FILES["picture"]["tmp_name"][$k], $path)){//執(zhí)行文件上傳操作 $result=true; }else{ $result=false; } } } if($result==true){ echo "文件上傳成功,請稍等..."; echo "<meta http-equiv=\"refresh\" content=\"3; url=index.php\">"; }else{ echo "文件上傳失敗,請稍等..."; echo "<meta http-equiv=\"refresh\" content=\"3; url=index.php\">"; } ?>
運(yùn)行結(jié)果如圖7.5所示。

圖7.5 在多文件上傳中應(yīng)用數(shù)組函數(shù)
注意
通過POST方法實(shí)現(xiàn)多文件上傳,在創(chuàng)建form表單時(shí),必須指定enctype="multipart/form-data"屬性。
推薦閱讀
- Java范例大全
- 零起步玩轉(zhuǎn)掌控板與Mind+
- Linux核心技術(shù)從小白到大牛
- Cocos2d-x游戲開發(fā):手把手教你Lua語言的編程方法
- Django:Web Development with Python
- NumPy Essentials
- Practical Game Design
- 青少年信息學(xué)競賽
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- 智能手機(jī)APP UI設(shè)計(jì)與應(yīng)用任務(wù)教程
- 零基礎(chǔ)學(xué)C語言(升級版)
- Raspberry Pi Robotic Projects
- Flink原理深入與編程實(shí)戰(zhàn):Scala+Java(微課視頻版)
- Instant SQL Server Analysis Services 2012 Cube Security
- Access 2010數(shù)據(jù)庫教程(微課版)