1. 程式人生 > >php CI框架單個file表單多檔案上傳例子

php CI框架單個file表單多檔案上傳例子

這裡使用的是CI2的版本,我們可以在一個file表單裡選擇多個檔案上傳。

先看看錶單怎麼寫:

要注意的是name需要使用陣列的形式,否則$_FILES變數僅僅獲取1個檔案的資訊。

<form action="/index.php" method="post" enctype="multipart/form-data">
  <input type="file" name="url[]" value="" multiple="" />
  <input type="submit" value="Submit"/>
</form>

CI控制器的程式碼:

由於CI2的uplaod元件不支援多檔案,所以我們改變了$_FILES變數,講陣列拆成相當於多個file表單的上傳

//$_FILES
//var_dump($_FILES);exit;
//array(1) { ["url"]=> array(5) { ["name"]=> array(1) { [0]=> string(24) "20180711142010_52340.jpg" } ["type"]=> array(1) { [0]=> string(10) "image/jpeg" } ["tmp_name"]=> array(1) { [0]=> string(14) "/tmp/phprlqfcU" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(132110) } } }
//array(1) { ["url"]=> array(5) { ["name"]=> array(3) { [0]=> string(24) "20180711142010_52340.jpg" [1]=> string(24) "20180711142010_92160.jpg" [2]=> string(24) "20180711142011_34008.jpg" } ["type"]=> array(3) { [0]=> string(10) "image/jpeg" [1]=> string(10) "image/jpeg" [2]=> string(10) "image/jpeg" } ["tmp_name"]=> array(3) { [0]=> string(14) "/tmp/phpXwIkvK" [1]=> string(14) "/tmp/phpW8HtsK" [2]=> string(14) "/tmp/phprPWEpK" } ["error"]=> array(3) { [0]=> int(0) [1]=> int(0) [2]=> int(0) } ["size"]=> array(3) { [0]=> int(132110) [1]=> int(70986) [2]=> int(115468) } } }
foreach ($_FILES['url']['name'] as $key => $image) {
    //set $_FILES value
    $fileKey = "url";
    $fileKeyNew = "url_{$key}";
    $_FILES[$fileKeyNew] = [
        'name' => $_FILES[$fileKey]['name'][$key],
        'type' => $_FILES[$fileKey]['type'][$key],
        'tmp_name' => $_FILES[$fileKey]['tmp_name'][$key],
        'error' => $_FILES[$fileKey]['error'][$key],
        'size' => $_FILES[$fileKey]['size'][$key],
    ];
    if ($this->upload->do_upload($fileKeyNew)) {
        $uploadData = $this->upload->data();
        $imageWidth = intval($uploadData['image_width']);
        $imageHeight = intval($uploadData['image_height']);
        //do something here
    } else {
        show_error($this->upload->display_errors(), 500);
    }
}