Thinkphp3.2簡單解決多文件上傳只上傳一張的問題


html簡單頁面:

index.html代碼:

<form action="{:U('index/upload')}" method="post" enctype="multipart/form-data">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    文件上傳:<input type="file" name = "test[]">
    <input type="submit" value = "提交">
</form>

控制器IndexController.class.php代碼:

<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $this->display();
    }
    public function upload(){
        if(IS_POST){
            $config = array(
                'maxSize'    =>    3145728,
                'rootPath'   =>    './Uploads/',
                'savePath'   =>    '',
                'saveName'   =>    array('uniqid', mt_rand(1,999999).'_'.md5(uniqid())),
                'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
                'autoSub'    =>    true,
                'subName'    =>    array('date','Ymd'),
            );
            $upload = new \Think\Upload($config);// 實例化上傳類
            $info   =   $upload->upload();
            if(!$info) {
                $this->error($upload->getError());
            }else{
                foreach($info as $file){
                    echo $file['savepath'].$file['savename'];
                }
            }
        }else{
            $this->display();
        }
    }
}

上傳結果顯示:

好多人在進行多文件上傳的時候,最后發現只是上傳了一張,主要就是命名所致,因為是同樣的名字,所以最后就剩一張圖片
解決方法:第一種:

$config = array(
                'maxSize'    =>    3145728,
                'rootPath'   =>    './Uploads/',
                'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
                'autoSub'    =>    true,
                'subName'    =>    array('date','Ymd'),
                'saveRule'   => '',
            );

置空$config里面的saveRule,上傳后的名稱為:59c8d38cdb968.jpg

若是感覺這種命名不可靠,可采取第二種方法:

$config = array(
                'maxSize'    =>    3145728,
                'rootPath'   =>    './Uploads/',
                'saveName'   =>    array('uniqid', mt_rand(1,999999).'_'.md5(uniqid())),
                'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
                'autoSub'    =>    true,
                'subName'    =>    array('date','Ymd'),
            );

設置$config中: 'saveName' => array('uniqid', mt_rand(1,999999).'_'.md5(uniqid())),
其最后的結果類似於:672563_30ad4d8a2aafc832363de8edc1940b5c59c8d44a303f9.jpg

然,命名可根據需要自行修改,多文件上傳方法很多,這里只是提供個簡單便捷的方法!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM