1. 程式人生 > >PHP的單個檔案上傳、多個單檔案上傳、多檔案上傳

PHP的單個檔案上傳、多個單檔案上傳、多檔案上傳

單檔案上傳

upload1.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>單檔案上傳</title>
</head>
<body>
    <form action="doAction5.php" method="post" enctype="multipart/form-data">
        請選擇您要上傳的檔案:
        <input type="file" name="myFile"/><br/>
        <input type="submit" value="上傳檔案"/>
    </form>
</body>
</html>

我們提交到 doAction5.php
<?php
/**
 * Created by PhpStorm.
 * User: DreamBoy
 * Date: 2016/4/8
 * Time: 21:39
 */
header('content-type:text/html;charset=utf-8');
print_r($_FILES);
exit();
我們先來看看單個檔案上傳後doAction5.php會輸出什麼?(檢視輸出結果的網頁原始碼)

沒有選擇檔案時:

選擇檔案後:

多個單檔案上傳

upload2.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多個單檔案上傳</title>
</head>
<body>
    <form action="doAction5.php" method="post" enctype="multipart/form-data">
        請選擇您要上傳的檔案:<input type="file" name="myFile1"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile2"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile3"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile4"/><br/>
        <input type="submit" value="上傳檔案"/>
    </form>
</body>
</html>

同樣提交到doAction5.php,執行檢視結果網頁原始碼。

沒有選擇檔案時:


上傳部分檔案時:


多檔案上傳

upload3.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多檔案上傳</title>
</head>
<body>
    <form action="doAction5.php" method="post" enctype="multipart/form-data">
        請選擇您要上傳的檔案:<input type="file" name="myFile[]"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile[]"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile[]"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile[]"/><br/>
        <input type="submit" value="上傳檔案"/>
    </form>
</body>
</html>

同樣提交到doAction5.php,執行檢視結果網頁原始碼。

注意:從結果我們可以發現這樣的多檔案提交方式,$_FILES將是一個3維陣列,此前的單檔案上傳或多個單檔案盛傳$_FILES是一個二維陣列。這裡也可以看出“多個單檔案上傳“和”多檔案上傳“的區別。

沒有選擇檔案時:


選擇部分檔案時:


混合方式提交檔案

upload4.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>混合方式檔案上傳</title>
</head>
<body>
    <form action="doAction5.php" method="post" enctype="multipart/form-data">
        請選擇您要上傳的檔案:<input type="file" name="myFile1"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile2"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile[]"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile[]"/><br/>
        請選擇您要上傳的檔案:<input type="file" name="myFile[]" multiple="multiple"/><br/>
        <input type="submit" value="上傳檔案"/>
    </form>
</body>
</html>
其中 
<input type="file" name="myFile[]" multiple="multiple"/>
multiple="multiple" 是html5中多檔案上傳的一種寫法。此時我們點選input後可以在選擇檔案介面按住 Ctrl 鍵選擇多個檔案。輸出結果與 寫了多次 
請選擇您要上傳的檔案:<input type="file" name="myFile[]"/>

相似。

同樣提交到doAction5.php,執行檢視結果網頁原始碼。

沒有選擇檔案時:


選擇部分檔案:


結果: