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');

 

 


免責聲明!

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



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