thinkphp5 Public method for uploading pictures and generating thumbnails of sharing

  • 2021-08-31 07:23:44
  • OfStack

Directly on the code, can be written in the public file common and inherited basic class, easy to call


/*
   * $name Uploaded for the form name Value 
   * $filePath For saving in the entry folder public Below uploads/ The following folder name, if not, will be automatically created 
   * $width Specify the thumbnail width 
   * $height Specify thumbnail height 
   *  Automatically generated thumbnails are saved in the $filePath Below the folder thumb Folder, automatically create 
   * @return array 1 One is the picture path, 1 The thumbnail path is as follows: 
   * array(2) {
     ["img"] => string(57) "uploads/img/20171211\3d4ca4098a8fb0f90e5f53fd7cd71535.jpg"
     ["thumb_img"] => string(63) "uploads/img/thumb/20171211/3d4ca4098a8fb0f90e5f53fd7cd71535.jpg"
    }
   */
  protected function uploadFile($name,$filePath,$width,$height)
  {
    $file = request()->file($name);
    if($file){
      $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS .$filePath;
      if(!file_exists($filePaths)){
        mkdir($filePaths,0777,true);
      }
      $info = $file->move($filePaths);
      if($info){
        $imgpath = 'uploads/'.$filePath.'/'.$info->getSaveName();
        $image = \think\Image::open($imgpath);
        $date_path = 'uploads/'.$filePath.'/thumb/'.date('Ymd');
        if(!file_exists($date_path)){
          mkdir($date_path,0777,true);
        }
        $thumb_path = $date_path.'/'.$info->getFilename();
        $image->thumb($width, $height)->save($thumb_path);
        $data['img'] = $imgpath;
        $data['thumb_img'] = $thumb_path;
        return $data;
      }else{
        //  Upload failed to get error message 
        return $file->getError();
      }
    }
  }

Related articles: