七牛云上传视频

近期客户需要做一个视频上传的功能,又嫌弃优酷、腾讯平台的广告,客户不差钱,因而选择了七牛云。

七牛云的开发者文档还是很详尽的,上传、重命名、转码,一应俱全,而且PHP,JAVA,PYTHON等各种语言sdk都很详细。


我用的是3.1版本的ThinkPHP,先去七牛开发者中心下载PHP的sdk到TP的扩展库Vendor目录下,命名为Qiniu。


接着新建QiniuAction.class.php

<?php
// 引入鉴权类 引入上传类
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;

class QiniuAction extends AppbaseAction {

    public function upload(){
        //防止盗用
        if(session('m_id') == ''){
            echo '小样,不给你上传!';
            die();
        }

        $return = array();
        $return['status'] = 0;
        
        
        //判断文件大小
        $maxSize = z_get_config('max_upload_video_size')  1024  1024;

        if($_FILES['uploadv'][size] > $maxSize){
            $return['info'] = '文件过大,不能超过'.z_get_config('max_upload_video_size').'M';
            echo json_encode($return);
            die();
        }

        //判断类型
        $arr_type = array('mp4','avi','rmvb','mp4','mpeg','wmv',,'mpv');
        $fileType = pathinfo($_FILES['uploadv']['name'],PATHINFO_EXTENSION);
        if(!in_array($fileType, $arr_type)){
            $return['info'] = '不支持此格式,请上传'.implode(',',$arr_type).'类型的视频';
            echo json_encode($return);
            die();
        }
        
        //引入库
        vendor('Qiniu.autoload');

        // 构建鉴权对象
        $accessKey = ak;
        $secretKey = sk;
        $auth = new Auth($accessKey, $secretKey);
        
        // 要上传的空间
        $bucket = 'train';
        
        // 要上传文件的本地路径
        $filePath = $_FILES['uploadv']['tmp_name'];

        // 上传到七牛后保存的文件名 采用id加当前时间
        $filename = 'qn_'.$mid.'_'.time().'.'.$fileType; 

        //要进行转码的转码操作 
        $fops = "avthumb/mp4/s/1280x720/vb/5m";

        //可以对转码后的文件进行使用saveas参数自定义命名,当然也可以不指定文件会默认命名并保存在当间
        $savekey = Qiniuase64_urlSafeEncode($bucket.':'.$filename);
        $fops = $fops.'|saveas/'.$savekey;

        $policy = array(
            'persistentOps' => $fops,
            'persistentPipeline' => $pipeline
        );
        $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);

        $uploadMgr = new UploadManager();

        list($ret, $err) = $uploadMgr->putFile($uptoken, null, $filePath);

        //返回
        if ($err !== null) {
            echo json_encode($err);
        } else {
            $return = $ret;
            $return['status'] = 1;
            $return['video'] = $filename;
            echo json_encode($return);
        }

    }
}


前台:


    <style type="text/css">
        .type2{display: none;}
        #progress{position:relative; margin-left:150px;  width:200px;padding: 1px; border-radius:3px; display:none;} 
        #bar {background-color: #D0333A; display:block; width:0%; height:30px;  border-radius:3px; color: #666; text-align: center; line-height: 30px;}
    </style>
    <div class="fabu">
        <p><span class="wd-fr"><a href="{:U('Home/Train/index')}">返回课程列表></a></span></p>
        <form method="post" action="{:U('Home/Train/fabu')}"  id="fabuForm" enctype="multipart/form-data" onsubmit="return jQuery(this).validationEngine('validate');">
        <input type="hidden" value="{$data_t['t_id']}" name="teacher_id">
        <input type="hidden" id="t-video" name="t_video">
        <div>
            <label>课程标题:</label><input type="text" name="t_name" class="validate[required,maxSize[100]]"/>
        </div>
        <div>
            <label>课程分类:</label>
            <volist name="list_lx" id="vo">
            <input type="radio" name="t_type" value="{$vo['d_value']}" class="validate[required,groupRequired[lx]]" <if condition="$i eq 1">checked</if>>{$vo['d_title']}&nbsp;&nbsp;
            </volist>
        </div>
        
        <div class="type2">
            <label>课程地点:</label>
            <input type="text" name="t_didian" class="validate[required,maxSize[50]]">
        </div>
        
        <div class="type2">
            <label>课程时间:</label>
            <input type="text" name="t_shijian" class="validate[required]" onFocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-M-d HH:mm:ss'})">
        </div>
        
        
        <div>
            <label>课程描述:</label>
            <input type="text" name="t_desc" class="validate[required,maxSize[500]]">
        </div>
        <div>
            <button type="submit" class="tijiao-btn wd-fr">提交</button>
        </div>
        </form>
        <form id="form1">
            <div><label for="">上传视频区:</label><input style="padding-left: 10px;display: inline-block;width: 600px;" type="file" name="uploadv" id="uploadvideo" accept="video/*"></div>
            <div id="progress"><div id="bar"></div></div>
            <div>
                <label for=""></label>
                <button type="button" id="upload-vb" class="tijiao-btn">上传</button>
            </div>
        </form>
    </div>
</div>
<div class="am-modal am-modal-alert" tabindex="-1" id="my-alert">
  <div class="am-modal-dialog">
    <div class="am-modal-hd">爱的温馨提示</div>
    <div class="am-modal-bd" id="tips-text">
          
    </div>
    <div class="am-modal-footer">
      <span class="am-modal-btn">我知道了</span>
    </div>
  </div>
</div>
<script type="text/javascript" src="/Skin/public/uploadify/jquery.uploadify.min.js"></script>

<script type="text/javascript" charset="utf-8" src="/Skin/public/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/Skin/public/ueditor/ueditor.all.min.js"> </script>
<script type="text/javascript" charset="utf-8" src="/Skin/public/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">
    var ue = UE.getEditor('editor',{
        toolbars:[
            ['bold', 'cleardoc', 'lineheight', '|',
                'customstyle', 'fontfamily', 'fontsize', '|',
                  'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 
                 'imagenone', 'imageleft', 'imageright', 'imagecenter', 'insertimage','attachment'
            ]
        ]
    });
</script>
<script src="/Skin/public/My97datepicker/WdatePicker.js" charset="utf-8"></script>
<script>
    $(function(){
        $('#uploadvideo').on('change',function(){
            var filename = $(this).val();
            var filetype = filename.substr(filename.lastIndexOf(".")).toLowerCase();
            arr = ['.rmvb','.mp4','.mpeg','.wmv','.avi','.mov','.mpv','.png'];
            //console.log(arr.toString().indexOf(filetype))
            if(arr.toString().indexOf(filetype)>-1){
                $('#upload-vb').on('click',fsubmit);
            }else{
                $('#upload-vb').unbind('click');
                alert('不支持此格式,请上传'+arr.join(',')+'格式视频')
            }
        })
<script>
function fsubmit(){ 
    var data = new FormData($('#form1')[0]); 
    $.ajax({ 
        url: '{:U('Home/Qiniu/upload')}', 
        type: 'POST', 
        data: data, 
        dataType: 'JSON', 
        cache: false, 
        processData: false,
        contentType: false,
        beforeSend: function(){
            $('#progress').show()
        },
        xhr: function(){
            //进度条
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(progress) {
                if (progress.lengthComputable) {
                    jindu = (progress.loaded / progress.total  100).toFixed(1);
                    $('#bar').css('width',jindu
2).html(jindu+'%')
                }
            };
            return xhr;
        },
        success: function(data) {
            if(data.status == 1){
                $('#t-video').val(data.video);
                tips('上传成功!');
            }else{
                tips(data.info);
            }
        },
        error: function(err){
            tips('上传失败!');
        },
        
    }); 
    return false; 
}
</script>
<include file="./Tpl/foot" />


这样就完成了,希望对你有所帮助,少走弯路。


七牛云上传视频
https://github.13sai.com/2016/11/28/89/
作者
13sai
许可协议