UploadController.php 12.2 KB
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;

use cmf\controller\RestUserBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Cache;
use think\Controller;
use think\Db;
use think\Validate;

/**
 * @title 文件上传
 * @description 文件上传
 * @package api\wxapp\controller
 */
class UploadController extends RestUserBaseController
{

    /**
     * @title 上传单个文件
     * @description 上传单个文件
     * @author Tiger Yang
     * @url /user/upload/one
     * @method POST
     *
     * @header name:XX-Token require:1 default: desc:登录标识
     * @header name:XX-Device-Type require:0 default:wxapp desc:设备类型
     *
     * @param name:file type:file require:1 other: desc:上传文件
     */
    public function one()
    {
        $file = $this->request->file('file');
        // 移动到框架应用根目录/public/upload/ 目录下
        $info     = $file->validate([
            /*'size' => 15678,*/
            'ext' => 'jpg,png,gif'
        ]);
        $fileMd5  = $info->md5();
        $fileSha1 = $info->sha1();

        $findFile = Db::name("asset")->where('file_md5', $fileMd5)->where('file_sha1', $fileSha1)->find();

        if (!empty($findFile)) {
            $this->success("上传成功!", ['url' => cmf_get_asset_url($findFile['file_path']), 'filename' => $findFile['filename']]);
        }
        $info = $info->move(ROOT_PATH . 'public' . DS . 'upload');
        if ($info) {
            $saveName     = $info->getSaveName();
            $originalName = $info->getInfo('name');//name,type,size
            $fileSize     = $info->getInfo('size');
            $suffix       = $info->getExtension();

            $fileKey = $fileMd5 . md5($fileSha1);

            $userId = $this->getUserId();
            Db::name('asset')->insert([
                'user_id'     => $userId,
                'file_key'    => $fileKey,
                'filename'    => $originalName,
                'file_size'   => $fileSize,
                'file_path'   => cmf_get_asset_url($saveName),
                'file_md5'    => $fileMd5,
                'file_sha1'   => $fileSha1,
                'create_time' => time(),
                'suffix'      => $suffix
            ]);

            $storage = cmf_get_option('storage');

            if (isset($storage['type'])&&$storage['type']=='Qiniu') {
                $this->uploadToQiniu($saveName);
            }
            $this->success("上传成功!", ['url' => cmf_get_asset_url($saveName), 'filename' => $originalName]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }

    }


    /**
     * 上传到七牛云
     * @param $save_name
     * @param bool $is_del_local
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function uploadToQiniu($save_name,$is_del_local=true){
        $plugin=Db::name('plugin')->field('config')->where(['name'=>'Qiniu'])->find();
        $config=json_decode($plugin['config'],true);

        $filePath = './../upload/'.$save_name;
        // 上传到七牛后保存的文件名
        $key =$save_name;
        require_once VENDOR_PATH . 'qiniu/php-sdk/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $config['accessKey'];
        $secretKey = $config['secretKey'];
        // 构建鉴权对象
        $auth = new Auth($accessKey,$secretKey);
        // 要上传的空间
        $bucket = $config['bucket'];

        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if($is_del_local){
            unlink($filePath);
        }
        if ($err !== null) {
            return ["err"=>1,"msg"=>$err,"data"=>""];
        } else {
            return ["err"=>0,"msg"=>"上传完成","data"=>cmf_get_image_url($ret['key'])];
        }
    }
    public function test() {
        return $this->uploadToQiniu('/15554568336598.png');
    }
    public function getToken() {
        $appid = config('appId');
        $secret = config('appSecret');
        if (Cache::get('access_token')) {
            return Cache::get('access_token');
        }
        $result = $this->curl_request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
        $data = json_decode($result,true);
        Cache::set('access_token',$data['access_token'],7000);
        return $data['access_token'];
    }
    /**
     * @title 获取海报图片地址
     * @description 获取海报图片地址
     * @url /user/upload/getPoster
     * @method POST
     *
     * @header name:XX-Token require:1 default: desc:登录标识
     * @header name:XX-Device-Type require:0 default:wxapp desc:设备类型
     * @param name:card_id require:1 default:1 desc:分享名片id
     *
     * @return img_url: type:file require:1 other: desc:图片地址。前面需要拼接域名
     */
    public function getPoster() {

        $validate = new Validate([
            'card_id'           => 'require',
        ]);
        $validate->message([
            'card_id.require'           => '缺少参数card_id!',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code'=>'40003','msg'=>$validate->getError()]);
        }
        //通过名片id 获取名片信息
        $info = Db::name('card')
            ->alias('c')
            ->join('user u','c.user_id = u.id','left')
            ->where(['c.id' => $data['card_id']])
            ->field('c.name,c.position,c.company,c.tel,c.email,u.avatar')
            ->find();
        $token = $this->getToken();
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$token;
        $arr = [
            'scene' => $data['card_id'].','.$this->userId
        ];
        //生成图片
        $xmlstr =  $this->curl_request($url,json_encode($arr));
        header("content-type: image/png");//如果要看报什么错,可以先注释调这个header
        $nickname = $info['name'];//姓名
        $position = $info['position'];//职称
        $company = $info['company'];//公司
        $tel = $info['tel'];//电话
        $email = $info['email'];//邮箱
        $tishi = '长按保存二维码';//提示
        $logourl = file_get_contents($info['avatar']);//微信头像
        $beijing = ROOT_PATH . 'public' . DS . 'upload/beijing.png';//海报最底层得背景
        //$youxiang = ROOT_PATH . 'public' . DS . 'upload/youxiang.png';//海报最底层得背景
        //$dianhua = ROOT_PATH . 'public' . DS . 'upload/dianhua.png';//海报最底层得背景

        //$youxiang = imagecreatefrompng($youxiang);
        //$dianhua = imagecreatefrompng($dianhua);
        $beijing = imagecreatefrompng($beijing);
        $logourl = imagecreatefromstring($logourl);

        $logourlfx = imagesx($logourl); // 获取宽度
        $logourlfy = imagesy($logourl); // 获取高度

        //3.使用固定的公式计算新的宽高
        $logourlsx = 300;
        $logourlsy = 300;
        //4.生成目标图像资源 微信头像
        $logourl_small = imagecreatetruecolor($logourlsx,$logourlsy);
        $color1 = imagecolorallocate($logourl_small, 255, 120, 43);
        imagefill($logourl_small, 0, 0, $color1);
        imageColorTransparent($logourl_small, $color1);
        //5.进行缩放
        imagecopyresampled($logourl_small,$logourl,0,0,0,0,$logourlsx,$logourlsy,$logourlfx,$logourlfy);



        $erweimaurl = imagecreatefromstring($xmlstr);
        $image_3 = imageCreatetruecolor(imagesx($beijing),imagesy($beijing));
        $color2 = imagecolorallocate($image_3, 0, 0, 0);
        imagefill($image_3, 0, 0, $color2);
        imageColorTransparent($image_3, $color2);
        imagecopyresampled($image_3,$beijing,0,0,0,0,imagesx($beijing),imagesy($beijing),imagesx($beijing),imagesy($beijing));
        //字体颜色
        $white = imagecolorallocate($image_3, 255, 255, 255);
        $rqys = imagecolorallocate($image_3, 255, 255, 255);
        $black = imagecolorallocate($image_3,255,255,255);
        $font = ROOT_PATH . 'public'."/static/font-awesome/fonts/simkai.ttf";  //写的文字用到的字体。字体最好用系统有得,否则会包charmap的错,这是黑体
        //imagettftext设置生成图片的文本
        //imagettftext($image_3,35,0,100,920,$black,$font,$nickname);//姓名
        //imagettftext($image_3,26,0,300,920,$black,$font,$position);//职称
        //imagettftext($image_3,26,0,100,980,$black,$font,$company);//公司
        //imagettftext($image_3,26,0,100,1040,$black,$font,$tel);//电话
        //imagettftext($image_3,26,0,100,1100,$black,$font,$email);//邮箱
        //imagettftext($image_3,26,0,440,1170,$black,$font,$tishi);//提示
        //imagecopymerge($image_3,$logourl_small, 240,250,0,0,$logourlsx,$logourlsy,100);//左,上,右,下,宽度,高度,透明度
        //imagecopymerge($image_3,$youxiang, 50,350,0,0,imagesx($youxiang),imagesy($youxiang),100);//左,上,右,下,宽度,高度,透明度
        //imagecopymerge($image_3,$dianhua, 50,390,0,0,imagesx($dianhua),imagesy($dianhua),100);//左,上,右,下,宽度,高度,透明度
        //imagecopymerge($image_3,$erweimaurl, 120,100,0,0,imagesx($erweimaurl),imagesy($erweimaurl), 100);
        //2.获得源文件的宽高
        $fx = imagesx($erweimaurl); // 获取宽度
        $fy = imagesy($erweimaurl); // 获取高度

        //3.使用固定的公式计算新的宽高
        $sx = $fx/1.8;
        $sy = $fy/1.8;
        //4.生成目标图像资源 小程序码
        $small = imagecreatetruecolor($sx,$sy);
        $color3 = imagecolorallocate($small, 255, 120, 43);
        imagefill($small, 0, 0, $color3);
        imageColorTransparent($small, $color3);
        //5.进行缩放
        imagecopyresampled($small,$erweimaurl,0,0,0,0,$sx,$sy,$fx,$fy);
        //imagecopymerge($image_3,$small, 450,875,0,0,imagesx($small),imagesy($small), 100);
        //生成图片
        $name = time().rand(1000,9999);
        imagepng($image_3,ROOT_PATH . 'public' . DS . 'upload/'.$name.'.png');//在浏览器上显示
        imagedestroy($image_3);
        $res['img_url'] = 'https://jnlexin.com/upload/'.$name.'.png';
        $this->success('获取成功',$res);
    }

    //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
    public function curl_request($url,$post='',$cookie='', $returnCookie=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            return $data;
        }
    }
}