Swoft 圖片上傳與處理


上傳

在Swoft下通過 

\Swoft\Http\Message\Server\Request -> getUploadedFiles()['image']

方法可以獲取到一個 Swoft\Http\Message\Upload\UploadedFile 對象或者對象數組(取決於上傳時字段是image還是image[])

打印改對象輸出:

object(Swoft\Http\Message\Upload\UploadedFile)#1813 (6) {
  ["clientFilename":"Swoft\Http\Message\Upload\UploadedFile":private]=>
  string(25) "蒙太奇配置接口.txt" ["clientMediaType":"Swoft\Http\Message\Upload\UploadedFile":private]=>
  string(10) "text/plain" ["error":"Swoft\Http\Message\Upload\UploadedFile":private]=> int(0) ["tmpFile":"Swoft\Http\Message\Upload\UploadedFile":private]=>
  string(55) "/var/www/swoft/runtime/uploadfiles/swoole.upfile.xZyq0d" ["moved":"Swoft\Http\Message\Upload\UploadedFile":private]=> bool(false) ["size":"Swoft\Http\Message\Upload\UploadedFile":private]=> int(710) }

都是私用屬性,無法訪問,但是可以通過對應方法訪問到

getClientFilename()      //得到文件原名稱
getClientMediaType()     //得到文件類型
getSize()        //獲取到文件大小

通過方法

moveTo()      //將文件從臨時位置轉移到目錄

上面方法返回為NULL,在移動文件到指定位置時最好判斷一下文件夾是否存在,不存在創建


 

圖片處理

借助 ImageMagick  工具完成

ubuntu下一鍵安裝

I. 安裝ImageMagick sudo apt-get install imagemagick II. 安裝imagemagick 的lib 供php調用 sudo apt-get install libmagick++-dev III. 調用當前的pecl安裝imagick pecl install imagick IV. 修改php.ini.重啟nginx服務器 在php.ini中添加: extension = imagick.so

在安裝完成后修改完 /etc/php/7.0/cli/php.ini 后發現 phpinfo 頁面打印出來沒有出現下面信息,於是又修改了/etc/php/7.0/fpm/php.ini 才出現下面信息

安裝 Intervention Image

composer require intervention/image

安裝完成后可以直接在頁面use

use Intervention\Image\ImageManager; $manager = new ImageManager(array('driver' => 'imagick')); //寬縮小到300px,高自適應
$thumb = $manager->make($path)->resize(300, null, function ($constraint) { $constraint->aspectRatio(); }); $thumb->save($path);

 完整代碼

namespace App\Controllers\Api; use Intervention\Image\ImageManager; use Swoft\Http\Message\Server\Request; use Swoft\Http\Message\Upload\UploadedFile; use Swoft\Http\Server\Exception\NotAcceptableException; use Swoft\Http\Server\Bean\Annotation\Controller; use Swoft\Http\Server\Bean\Annotation\RequestMapping; use Swoft\Http\Server\Bean\Annotation\RequestMethod; class FileController { //圖片可接受的mime類型
    private static $img_mime = ['image/jpeg','image/jpg','image/png','image/gif']; /** * 文件上傳 * @RequestMapping(route="image",method=RequestMethod::POST) */
    public static function imgUpload(Request $request){ $files = $request->getUploadedFiles()['image']; if(!$files){ throw new NotAcceptableException('image字段為空'); } if(is_array($files)){ $result = array(); foreach ($files as $file){ self::checkImgFile($file); $result[] = self::saveImg($file); } }else{ self::checkImgFile($files); return self::saveImg($files); } } /** * 保存圖片 * @param UploadedFile $file */
    protected static function saveImg(UploadedFile $file){ $dir = alias('@upload') . '/' . date('Ymd'); if(!is_dir($dir)){ @mkdir($dir,0777,true); } $ext_name = substr($file->getClientFilename(), strrpos($file->getClientFilename(),'.')); $file_name = time().rand(1,999999); $path = $dir . '/' . $file_name . $ext_name; $file->moveTo($path); //修改移動后文件訪問權限,文件默認沒有訪問權限
        @chmod($path,0775); //生成縮略圖
        $manager = new ImageManager(array('driver' => 'imagick')); $thumb = $manager->make($path)->resize(300, null, function ($constraint) { $constraint->aspectRatio(); }); $thumb_path = $dir. '/' . $file_name . '_thumb' .$ext_name; $thumb->save($dir. '/' . $file_name . '_thumb' .$ext_name); @chmod($thumb_path,0775); return [ 'url' => explode(alias('@public'),$path)[1],
            'thumb_url' => explode(alias('@public'),$thumb_path)[1] ]; } /** * 圖片文件校驗 * @param UploadedFile $file * @return bool */
    protected static function checkImgFile(UploadedFile $file){ if($file->getSize() > 1024*1000*2){ throw new NotAcceptableException($file->getClientFilename().'文件大小超過2M'); } if(!in_array($file->getClientMediaType(), self::$img_mime)){ throw new NotAcceptableException($file->getClientFilename().'類型不符'); } return true; } }

使用

FileController::imgUpload($request);

說明

當前保存文件路徑為 alias("@upload"),需要在 /config/define.php 手動填上該路徑

$aliases = [ '@root'       => BASE_PATH,
    '@env'        => '@root',
    '@app'        => '@root/app',
    '@res'        => '@root/resources',
    '@runtime'    => '@root/runtime',
    '@configs'    => '@root/config',
    '@resources'  => '@root/resources',
    '@beans'      => '@configs/beans',
    '@properties' => '@configs/properties',
    '@console'    => '@beans/console.php',
    '@commands'   => '@app/command',
    '@vendor'     => '@root/vendor',
    '@public'     => '@root/public',     //public目錄,也是nginx設置站點根目錄
    '@upload'     => '@public/upload'    //上傳目錄
];

 

Swoft 不提供靜態資源訪問,可以使用nginx托管

配置nginx 

vim /etc/nginx/sites-avaiable/default
server { listen 80 default_server; listen [::]:80 default_server; # 域名設置 server_name eko.xiao.com; #設置nginx根目錄 root /var/www/html/swoft/public; # 將所有非靜態請求轉發給 Swoft 處理 location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Connection "keep-alive"; proxy_pass http://127.0.0.1:9501;
 } location ~ \.php$ { proxy_pass http://127.0.0.1:9501;
 } # 靜態資源使用nginx托管 location ~* \.(js|map|css|png|jpg|jpeg|gif|ico|ttf|woff2|woff)$ { expires max; } }

 


免責聲明!

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



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