七牛云持久化上传图片及生成缩略图,多文件打包下载

上代码之前,我想吐槽一下七牛云的DEMO, 写的确实不咋地。

废话不多说,咱们开始吧。

项目框架TP5.1 , 之前别人写了一点,懒得改七牛云的SDK目录,强迫症患者将就着看看吧,

qiniu的phpSDK 放在了vendor文件夹下。

1. 持久化处理上传及生成缩略图。 由于上传的图片较大 20M + , 所以采用了持久化处理上传,putfile  20M的图片是不让你上传的。

newFilename 就是保存在七牛云上的原图key, 

oldFilePath 服务器上图片的地址,服务器缓存中的地址

persistentops :  对图片进行的操作,如果有多个操作则用 , 隔开。 

persistentNotifyUrl 是异步返回的通知地址, 在这个方法中我们要进行的操作就是保存缩略图到服务器并删除七牛云上的缩略图。

完成的操作:设置了原图的key, 将原图保存后,生成 200*200的缩略图保存在七牛云。

private function uploadImgPost($newFilename, $oldFilepath){
        set_time_limit(0);
        $t1 = microtime(true);
        require_once APP_PATH . '/../vendor/qiniu/autoload.php';
        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        //生成保存文件的key
        $explode = explode(".", $newFilename);
        $thumbKey = $explode[0] . "_thumb" .".". $explode[1];
        $entry = $this->bucket .":". $thumbKey;
        $encodedEntryURI = \Qiniu\base64_urlSafeEncode($entry);
        $array = [
            'persistentOps'=>'imageView2/2/w/200/h/200/q/70/ignore-error/1/|saveas/'.$encodedEntryURI,        //处理方式  200*200 缩略图, 并保存缩略图
            'persistentNotifyUrl'=> url('appindex/Files/uploadImgNotify', '', true, true),
        ];
        //生成上传Token
        $token = $auth->uploadToken($this->bucket, null, 3600, $array );
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $newFilename, $oldFilepath);
        if ($err !== null) {
            return ['code' => -1, 'msg' =>'上传失败'];
        } else {
            $t2 = microtime(true);
            file_put_contents('time.log', "七牛云上传时间:" . ($t2 - $t1) . "秒", FILE_APPEND );
            //返回图片的完整URL
            $newFilepath = $this->httpPre . $this->domain . "/" . $ret['key'];
            //保存在本地的缩略图
            $thumbUrl = $this->getThumbUrlFromQiniuKey($ret['key']);
            return ['code' => 1, 'msg' => '上传成功', 'data' => ['url'=> $newFilepath, 'previewUrl' => $thumbUrl]];
        }
    }

以下代码为异步方法

deleteFile 方法就不贴出来了,七牛云上有, 很简单。

最后返回一个json字符串的通知,否则多媒体队列会显示失败。 

   /**
     * 上传图片后, 保存生成的缩略图到本地,并删除保存在空间中的缩略图
     * Function uploadImgNotify
     * @author mselect <[email protected]>
     * @DateTime 2019/5/16
     */
    public function uploadImgNotify(){
        $arr = $this->request->param();
        if( !empty($arr['code']) && $arr['code'] == 0 ){
            //成功
            $items = $arr['items'];
            $path = ROOT_PATH . $this->thumbSavePath;

            if(!is_dir($path)){
                mkdir($path, 0777, true);
            }

            foreach($items as $item){
                if(strpos($item['cmd'], 'saveas') !== false){
                    //将资源下载,然后删除
                    $url = $this->httpPre . $this->domain . '/' . $item['key'];
                    $back = file_put_contents($path . $item['key'] , file_get_contents($url));
                    if($back <=0 ){
                        unlink($path . $item['key']);
                    }else {
                        //将七牛云上的缩略图文件删除
                        $this->deleteFile($item['key']);
                    }
                }
            }
            $resp = array('ret' => 'succeed');
        }else {
            $resp = array('ret' => 'failed');
        }
        return json($resp);
    }

2. 多文件打包zip 下载

keys 是保存了所有要打包的文件的key 数组

zipKey 为保存在七牛云上的压缩包key 

完成工作: 将keys数组中的所有文件打包成zip , 保存在七牛云上,异步通知方法将压缩包下载。

pipeline 为自己创建的多媒体队列名称

key = test.zip  这个是个坑, 这个文件是个默认文件,你需要上传一个test.zip (随便上传一个很小的压缩包)到七牛云。

    /**
     *
     * 将作品的中所有水印图片压缩成zip下载
     * Function mkzip
     * @author mselect <[email protected]>
     * @DateTime 2019/5/13
     * @param $keys       array      要压缩的文件
     */
    public function mkzip($keys, $zipKey){

        require_once APP_PATH . '/../vendor/qiniu/autoload.php';
        $auth = new Auth($this->accessKey, $this->secretKey);
        $pipeline = 'mkzip';
        $key =  "test.zip"; //d5b37d559fbec90b0cdc_water
        $pfop = new PersistentFop($auth, null);
        $fops = 'mkzip/2';
        foreach($keys as $value){
            $fops .= '/url/' . \Qiniu\base64_urlSafeEncode($value);
        }
        $zipKey = $zipKey . ".zip";
        $fops .= '|saveas/' . \Qiniu\base64_urlSafeEncode($this->bucket . ":" . $zipKey);
        $notify_url = url('appindex/Files/mkzipNotify', '', true, true);
        $force = false;
        list($id, $err) = $pfop->execute($this->bucket, $key, $fops, $pipeline, $notify_url, $force);
        file_put_contents('imgwater.log', "处理队列ID: $id , 回调地址:$notify_url \r\n", FILE_APPEND);
        if($err !==null){
            return ['code' => -1, 'msg' => '打包失败了'];
        }else {
            //轮询队列执行完成后才返回
            while(true){
                $url = "http://api.qiniu.com/status/get/prefop?id=" . $id;
                $json = file_get_contents($url);
                $arr = json_decode($json, true);
                if($arr['code'] == 0 ){
                    break;
                }else if($arr['code'] == 3 || $arr['code'] == 4){
                    file_put_contents('imgwater.log', $arr['desc'] . "\r\n", FILE_APPEND);
                    return ['code' => -1, 'msg'=> $arr['desc']];
                }
            }
            return ['code' => 1, 'msg' => '压缩成功', 'data' => ['fileKey' => $this->httpPre . $this->domain . "/" . $zipKey]];
        }
    }

下载压缩包的方法与

以上异步通知方法类似,不再赘述。

 

以上方法如有问题,请及时联系我

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章