TP5单文件、多文件上传

文件上传可以直接引用框架自定义的文件上传类 use thinkFile; 

这里封装一个文件上传的model,以便重复利用 UploadFiles.php

1、控制器层

use appadminmodelUploadFiles;    // 使用文件上传model

2、model层

<?php
namespace appadminmodel;
use thinkModel;       // 使用Model
use thinkFile;           // 使用文件上传类
use thinkValidate;    // 使用文件上传验证
use thinkRequest;   // 接值时使用

/**
 * 封装文件上传model
 */
class UploadFiles extends Model
{
        
    /**
     * 单文件上传
     * @param  [type] $file   [description]
     * @return [type] string  [description]
     */
    public function uploadOne($file){

        $filePath = ROOT_PATH . 'public' . DS . 'uploads'; // 项目物理路径
        $rootPath = Request::instance()->root(true);         // 项目根路径
        if (!file_exists($filePath)) {
            mkdir($filePath);
        }else{          
            $info = $file
                    ->validate([
                        'size'=>156780,
                        'ext'=>'jpg,png,gif'
                      ])
                    ->move($filePath);
            if($info){
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                return $rootPath."/uploads/".$info->getSaveName();      // 返回带域名的图片路径
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                // return $info->getFilename();
            }else{
                return $file->getError();
            }
        }
    }

    /**
     * 多文件上传
     * @param  [type] $files   [description]
     * @return [type] array    [description]
     */
    public function uploadAll($files)
    {
        $filePath = ROOT_PATH . 'public' . DS . 'uploads'; // 项目物理路径
        $rootPath = Request::instance()->root(true);         // 项目根路径
        $array = array();
        foreach ($files as $key => $file) {
            if (!file_exists($filePath)) {
                mkdir($filePath);
            }else{          
                $info = $file
                        ->validate([
                            'size'=>156780,
                            'ext'=>'jpg,png,gif'
                          ])
                        ->move($filePath);
                if($info){
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    $imgPath = $rootPath."/uploads/".$info->getSaveName();   // 返回带域名的图片路径
                    array_push($array,$imgPath);
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    // return $info->getFilename();
                }else{
                    return $file->getError();
                }
            }
        }
        return $array;
    }


}

原文地址:https://www.cnblogs.com/lpblogs/p/7277366.html