Common.php 7.1 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use Qiniu\Storage\ResumeUploader;
use Qiniu\Storage\UploadManager;
use think\Config;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init','getReportTypeList'];
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng     经度
     * @param string $lat     纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');

        $config = get_addon_config('qiniu');

        // 构建鉴权对象
        $auth = new \Qiniu\Auth($config['accessKey'], $config['secretKey']);
        // 生成上传 Token
        $token = $auth->uploadToken($config['bucket'], null, 3600, ['saveKey' => ltrim($config['savekey'], '/')]);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filesize = $this->request->post("filesize");
            $filename = $this->request->post("filename");
            if ($action == 'merge') {
                if ($config['uploadmode'] == 'server') {
                    $attachment = null;
                    //合并分片文件
                    try {
                        $upload = new Upload();
                        $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }

                $contexts = $this->request->post("contexts/a", []);
                $uploader = new ResumeUploader($token, null, null, $filesize);
                list($ret, $err) = $uploader->setContexts($contexts)->makeFile($filename);
                if ($err !== null) {
                    $this->error("上传失败");
                } else {
                    $this->success("上传成功", '', ['url' => '/' . $ret['key'], 'fullurl' => cdnurl('/' . $ret['key'], true), 'hash' => $ret['hash']]);
                }
            } else {
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $file = $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }

                //上传分片文件
                //$file = $this->request->file('file');
                $filesize = $file->getSize();
                //合并分片文件
                $uploader = new ResumeUploader($token, null, fopen($file->getRealPath(), 'rb'), $filesize);
                $ret = $uploader->uploadChunk($chunkindex, $file, $filesize);
                $this->success("上传成功", "", $ret);
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);

                $suffix = $upload->getSuffix();
                $md5 = md5_file($file->getRealPath());
                $search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
                $replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
                $savekey = ltrim(str_replace($search, $replace, $config['savekey']), '/');

                $attachment = $upload->upload($savekey);
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            //文件绝对路径
            $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();

            //上传到七牛后保存的文件名
            $saveKey = ltrim($attachment->url, '/');

            try {
                // 调用 UploadManager 的 putFile 方法进行文件的上传。
                list($ret, $err) = $uploadMgr->putFile($token, $saveKey, $filePath);

                if ($err !== null) {
                    throw new \Exception("上传失败");
                }
                //成功不做任何操作
            } catch (\Exception $e) {
                $attachment->delete();
                @unlink($filePath);
                $this->error("上传失败");
            }
            $data = [
                'url' => $attachment->url,
                'fullurl' => cdnurl($attachment->url, true),
                'type'=>$attachment->imagetype
            ];
            if ($attachment->filesize > 1000000){
                $data['filesize'] = number_format($attachment->filesize/1000000,2).'MB';
            }else{
                $data['filesize'] = number_format($attachment->filesize/1000,2).'KB';
            }
            $this->success(__('Uploaded successful'),$data);
        }
    }

    /**
     *  获取举报类型
     */
    public function getReportTypeList(){
      $report_type = model('report_type')->order('weigh','desc')->select();
      $this->success('获取类型成功',$report_type);
    }
}