thinkphp5.1 封装文件上传模块

时间:2020-04-10
本文章向大家介绍thinkphp5.1 封装文件上传模块,主要包括thinkphp5.1 封装文件上传模块使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我在app\extra模块下新建一个文件上传类 ExtraUpload.php,目前只支持image、audio、video、file四种类型的文件,可通过config属性扩展。下面就是我封装的类。

<?php
namespace app\extra;
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

//适配移动设备图片上传
use think\Exception;
use think\facade\Request;

class ExtraUpload{
    
    /**
     * 默认上传配置
     * @var array
     */
    private $config = [
        'image' => [
            'validate' => [
                'size' => 10*1024*1024,
                'ext'  => 'jpg,png,gif,jpeg',
            ],
            'rootPath'      =>  './Uploads/images/', //保存根路径
        ],
        'audio' => [
            'validate' => [
                'size' => 100*1024*1024,
                'ext'  => 'mp3,wav,cd,ogg,wma,asf,rm,real,ape,midi',
            ],
            'rootPath'      =>  './Uploads/audios/', //保存根路径
        ],
        'video' => [
            'validate' => [
                'size' => 100*1024*1024,
                'ext'  => 'mp4,avi,rmvb,rm,mpg,mpeg,wmv,mkv,flv',
            ],
            'rootPath'      =>  './Uploads/videos/', //保存根路径
        ],
        'file' => [
            'validate' => [
                'size' => 5*1024*1024,
                'ext'  => 'doc,docx,xls,xlsx,pdf,ppt,txt,rar',
            ],
            'rootPath' =>  './Uploads/files/', //保存根路径
        ],
    ];
    private $domain;
    function __construct()
    {
        //获取当前域名
        $this->domain = Request::instance()->domain();
    }

    public function upload($fileName){
       if(empty($_FILES) || empty($_FILES[$fileName])){
           return '';
       }
       try{
           $file = request()->file($fileName);
           if (is_array($file)){
               $path = [];
               foreach ($file as $item){
                   $path[] =  $this->save($item);
               }
           } else {
               $path = $this->save($file);
           }
           return $path;
       } catch (\Exception $e){
           $arr = [
               'status' => 0,
               'message' => $e->getMessage(),
           ];
           header('Content-Type: application/json; charset=UTF-8');
           exit(json_encode($arr));
       }
   }
   public function uploadDetail($fileName){
       if(empty($_FILES) || empty($_FILES[$fileName])){
           return [];
       }
       try{
           $file = request()->file($fileName);
           if (is_array($file)){
               $path = [];
               foreach ($file as $item){
                   $detail = $item->getInfo();
                   $returnData['name'] = $detail['name'];
                   $returnData['type'] = $detail['type'];
                   $returnData['size'] = $detail['size'];
                   $returnData['filePath'] = $this->save($item);
                   $returnData['fullPath'] = $this->domain.$returnData['filePath'];
                   $path[] = $returnData;
               }
           } else {
               $detail = $file->getInfo();
               $returnData['name'] = $detail['name'];
               $returnData['type'] = $detail['type'];
               $returnData['size'] = $detail['size'];
               $returnData['filePath'] = $this->save($file);
               $returnData['fullPath'] = $this->domain.$returnData['filePath'];
               $path = $returnData;
           }
           return $path;
       } catch (\Exception $e){
           $arr = [
               'status' => 0,
               'message' => $e->getMessage(),
           ];
           header('Content-Type: application/json; charset=UTF-8');
           exit(json_encode($arr));
       }
   }
   private function getConfig($file){
       $name = pathinfo($file['name']);
       $end = $name['extension'];
       foreach ($this->config as $key=>$item){
           if ($item['validate']['ext'] && strpos($item['validate']['ext'], $end) !== false){
               return $this->config[$key];
           }
       }
       return null;
   }
   private function save(&$file){
       $config = $this->getConfig($file->getInfo());
       if (empty($config)){
           throw new Exception('上传文件类型不被允许!');
       }
       // 移动到框架应用根目录/uploads/ 目录下
       if ($config['validate']) {
           $file->validate($config['validate']);
           $result = $file->move($config['rootPath']);
       } else {
           $result = $file->move($config['rootPath']);
       }
       if($result){
           $path = $config['rootPath'];
           if (strstr($path,'.') !== false){
               $path = str_replace('.', '', $path);
           }
           return $path.$result->getSaveName();
       }else{
           // 上传失败获取错误信息
           throw new Exception($file->getError());
       }
   }
}

怎么使用?

接口使用

在app\api下新建一个upload.php,代码如下:

<?php
namespace app\api\controller;


class Upload
{

    public function upload(){
        $p = new \app\extra\ExtraUpload();
        $file = $p->upload('file');
        $this->returnMessage($file);
    }
    public function uploadDetail(){
        $p = new \app\extra\ExtraUpload();
        $file = $p->uploadDetail('file');
        $this->returnMessage($file);
    }
    private function returnMessage($data){
        $arr = [
            'status' => 1,
            'message' => '文件上传成功',
            'data'=> $data,
        ];
        header('Content-Type: application/json; charset=UTF-8');
        exit(json_encode($arr));
    }
}

内部调用,从上面接口可以看到直接执行一下代码即可实现内部调用

$p = new \app\extra\ExtraUpload();
$file = $p->uploadDetail('file');

 

$flag 上一页 下一页