Home  >  Article  >  PHP Framework  >  How ThinkPHP implements the upload and transcoding functions of Qiniu Cloud Storage

How ThinkPHP implements the upload and transcoding functions of Qiniu Cloud Storage

PHPz
PHPzOriginal
2023-04-11 09:15:511219browse

With the continuous development of Internet technology, the application of cloud storage is becoming more and more widespread, especially video websites and audio websites. These websites provide users with online viewing or online listening, and behind all this is cloud storage Technical support. Qiniu Cloud Storage, as a leading domestic cloud storage service provider, has a wide range of applications in the Internet industry, especially in multimedia uploading, storage, acceleration and distribution, etc., and has good performance. So, in this article, we will use ThinkPHP as an example to introduce the upload and transcoding functions of Qiniu Cloud Storage.

1. What is ThinkPHP

ThinkPHP is a free and open source PHP framework created by Chinese developers. It allows developers to quickly develop applications through simple configuration and encapsulation. ThinkPHP fully considers the actual needs of web development and vigorously integrates excellent works in the open source community to fully meet the needs of web developers.

2. What is Qiniu Cloud Storage

Qiniu Cloud Storage is a fast and simple cloud storage service provider that focuses on providing users with reliable, efficient and secure cloud storage. Serve. Qiniu Cloud Storage can provide storage, management and distribution services for multimedia files. Users only need to upload their own multimedia files to Qiniu Cloud Storage, and they can be accelerated through Qiniu's CDN, allowing users to access faster and smoother these files.

3. How ThinkPHP implements the upload of Qiniu Cloud Storage

To use the upload function of Qiniu Cloud Storage under the ThinkPHP framework, you first need to introduce the authentication class and Qiniu Cloud Storage under the project SDK, handle the authentication information when uploading:

require_once('Auth.php');
require_once('Config.php');
require_once('autoload.php');//引入七牛SDK

$accessKey = '可以从七牛后台获得';
$secretKey = '可以从七牛后台获得';

//鉴权对象
$auth = new Auth($accessKey, $secretKey);  

//生成上传Token
$bucket = '要上传的bucket名称';//bucket名称
$key = '要生成的文件名';//文件名称
$options['returnBody'] = '{"name": $(fname), "size": $(fsize), "hash": $(etag), "url": "http://example.com/$(key)"}';//要返回的信息
$policy = array(
    'returnBody'      =>  json_encode($options['returnBody']),//返回给客户端的信息
    'saveKey'         =>  $key,//上传的文件名
);
$upToken = $auth->uploadToken($bucket, null, 3600, $policy);//生成上传Token

After that, use the Javascript SDK of Qiniu Cloud Storage in the page to realize the file selection and upload function:

<script src="http://cdn.staticfile.org/plupload/2.1.1/plupload.full.min.js"></script>
<script type="text/javascript">
    //设置上传参数
    var uploader = new plupload.Uploader({
        browse_button: 'browse', //触发选择文件对话框的按钮
        url: 'http://upload.qiniup.com/', //服务器端的上传页面地址
        flash_swf_url: 'path/of/plupload/Moxie.swf',//swf文件,用于解决跨域或不支持xhr2的浏览器上传问题
        silverlight_xap_url: 'path/of/plupload/Moxie.xap',//silverlight文件,用于解决跨域或不支持xhr2的浏览器上传问题
        chunk_size: '4mb',//分块上传的块大小
        multi_selection: false,//是否支持多选
        filters: {
            max_file_size: '10mb',//最大文件大小
            mime_types: [
              {title: "Image files", extensions: "jpg,gif,png,jpeg,webp"},
              {title: "Video files", extensions: "avi,mp4,mkv,flv,mov"},
              {title: "Audio files", extensions: "mp3,wma,ogg,wav"},
            ]//上传文件类型限制
        },
        multipart: true,//是否将文件分块上传
        multipart_params: {//通常只能上传原始二进制文件到流中,而文件的信息必须存在于HTTP请求的上下文中
            key: '文件名称',
            token: '{$uptoken}',
        }
    });

    //绑定触发上传的事件
    uploader.bind('FilesAdded', function(up, files) {
       uploader.start();//当文件被添加到上传队列后开始上传流程
    });

    //绑定上传过程的事件
    uploader.bind('UploadProgress', function(up, file) {
        var percent = file.percent;
    });

    //绑定上传成功的事件
    uploader.bind('FileUploaded', function(up, file, info) {
        var result = JSON.parse(info.response);
        console.log(result.url);//获取上传成功后的文件链接
    });

    //绑定上传失败的事件
    uploader.bind('Error', function(up, err) {
        if(err.code==-601){//文件格式不符合
           console.log('上传失败:文件格式不符合要求');
        }else if(err.code==-200){//文件太大
           console.log('上传失败:文件大小超出限制');
        }else{
           console.log(err.message);//其他失败信息
        }
    });

    //启动上传
    uploader.init();
</script>

4. How to use ThinkPHP 7 Transcoding function of Niuyun Storage

For some video websites, audio websites, etc., the audio and video files uploaded by users often need to be transcoded to make them meet the requirements of the website. At this time, you need to use seven Niu Cloud Storage has a transcoding function. It can automatically transcode audio and video and generate playback links in various formats to facilitate users to watch or listen online. Under the ThinkPHP framework, using the transcoding function of Qiniu Cloud Storage requires installing the composer package. Use composer to install:

composer require qiniu/php-sdk

After the installation is completed, audio and video transcoding can be achieved through the PHP SDK. Specific transcoding operations You can refer to:

require __DIR__ . '/vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

$accessKey = 'your accessKey';
$secretKey = 'your secretKey';

//鉴权对象
$auth = new Auth($accessKey, $secretKey);

//空间名称
$bucket = 'your bucket';

//文件保存键名
$key = 'your key';

//上传文件的本地路径
$filePath = 'your filepath';

//上传的转码参数
$pfop = "avthumb/mp4";

//对于使用自己私有的codec库时需要制定so路径, 在<SoSdkPath>中填入so文件路径。其他情况则没必要, 该参数可以不填。
$encoding_codec_lib_path = null;

$urlbase64 = \Qiniu\base64_urlSafeEncode($bucket . ':' . $key);

//设置回调的URL地址
$notifyUrl = 'http://yourdomain.com/callback.php';

//转码完成后回调指向的地址
$fops = $pfop. '|saveas/' . \Qiniu\base64_urlSafeEncode("$bucket:$key") . '|notifyURL/' . $notifyUrl;

//初始化BucketManager
$config = new \SDK\Qiniu\Config();
$config->zone = new \SDK\Qiniu\Zone\Zhuanqu();
$bucketManager = new BucketManager($auth, $config);

//调用fetch方法拉取网络上的一个资源,该资源用于转码,该方式不支持本地音视频文件的转码处理
$fetchResult = $bucketManager->fetch($url, $bucket, $key, $pfop);

if($fetchResult != null){
    //上传流程
    $uploadMgr = new UploadManager($config);
    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath ,null,$encoding_codec_lib_path);
    if ($err !== null) {
        echo '上传失败:', $err->message(), "\n";
    } else {
        echo '上传成功:', $ret['key'], "\n";

        //持久化处理并等待处理结果
        $persistentOps = $fops;//音视频持久化处理的详细指令,多个指令用;隔开
        $pipeline = '';//进行转码的队列名称,不传此参数将使用默认队列
        $force = true;//强制覆盖已有的同名文件

        //调用持久化处理接口实现音视频转码等持久化操作(不支持本地音视频文件的转码处理)。
        list($ret, $err) = $bucketManager->persistentFop($bucket, $key, $persistentOps, $pipeline, $force);
        if ($err !== null) {
            var_dump($err);
        } else {
            var_dump($ret);
        }
    }
}

5. Conclusion

I hope that through the introduction of this article, everyone can have a deeper understanding of the upload and transcoding functions of Qiniu Cloud Storage, and implement Qiniu under the ThinkPHP framework Cloud storage upload and transcoding operations. To learn a piece of knowledge, only by continuous practice and summary can you truly master and apply it freely.

The above is the detailed content of How ThinkPHP implements the upload and transcoding functions of Qiniu Cloud Storage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn