简单解决thinkphp3.2对于多文件上传的问题(命名)

浏览:2939 发布日期:2017/09/25 分类:技术分享 关键字: 多文件上传 thinkphp3.2 多文件上传命名
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

当然,命名可根据需要自行修改,多文件上传方法很多,这里只是提供个简单便捷的方法!

附件 thinkphp3.2_full.zip ( 2.49 MB 下载:27 次 )

最佳答案
评论( 相关
后面还有条评论,点击查看>>