Commit ea336466 authored by 杨培's avatar 杨培

优化视频上传组件,更多使用vue,增加上传完成状态事件等

新增缩略图上传组件
增加七牛上传回调验证接口
其它各种调整
parent 5d021c2f
......@@ -5,9 +5,10 @@
* Date: 16/9/29
* Time: 16:05
*/
namespace common\libs;
namespace common\components;
use yii\base\Object;
use yii\helpers\Url;
use Qiniu\Auth;
class Qiniu extends Object
......@@ -88,15 +89,61 @@ class Qiniu extends Object
$config = $this->storages[$storage];
$callbackUrl = Url::to(['qiniu-callback/rem-upload'], true);
$policy = [
'returnBody' => $returnBody,
'saveKey' => $filename,
'fsizeLimit' => $config['fsizeLimit'],
'mimeLimit' => $config['mimeLimit']
'mimeLimit' => $config['mimeLimit'],
'callbackUrl' => 'http://t.pp.cc/tmp/qiniu_callback.php',
'callbackBody' => 'key=$(key)&fsize=$(fsize)&time=$(year)-$(mon)-$(day) $(hour)%3A$(min)%3A$(sec)'
];
$auth = $this->getAuthInstance();
return $auth->uploadToken($config['bucket'], null, $deadSeconds, $policy);
}
public function decodeUploadToken($token)
{
$arr = explode(':', $token);
if (count($arr) != 3) {
return null;
}
list($accessKey, $sign, $data) = $arr;
$dataJson = \Qiniu\base64_urlSafeDecode($data);
$dataArr = json_decode($dataJson, true);
if (!isset($dataArr['scope'])) {
return null;
}
//寻找配置
$config = null;
foreach ($this->storages as $storage => $cfg) {
if ($cfg['bucket'] == $dataArr['scope']) {
$config = $cfg;
break;
}
}
if ($config === null) {
return null;
}
//验证 Token 是否一致
$auth = $this->getAuthInstance();
$reToken = $auth->signWithData($dataJson);
if ($token != $reToken) {
return null;
}
return $dataArr;
}
}
\ No newline at end of file
......@@ -49,7 +49,7 @@ return [
],
],
'qiniu' => [
'class' => 'common\libs\Qiniu',
'class' => 'common\components\Qiniu',
'accessKey' => 'n85SCPB9uO2v32az-3TRFsZCXwJu7YddyzLRYXg-',
'secretKey' => 'KDl3b7aLpj7n9YZ07lHGivVY4c_Q-0QSM0TZ_-XS',
'storages' => [
......
......@@ -16,24 +16,24 @@ class MyCourseController extends \yii\web\Controller
public function actionPublish()
{
/* @var \common\libs\Qiniu $qiniu */
/* @var \common\components\Qiniu $qiniu */
$qiniu = Yii::$app->qiniu;
//$auth = Yii::$app->qiniu->getAuthInstance();
$returnBody = '{"uuid":$(uuid), "size": $(fsize), "w":$(imageInfo.width), "h":$(imageInfo.height), "hash":$(etag)}';
$returnBody = '{"uuid":$(uuid), "key": "$(key)", "size": $(fsize), "w":$(imageInfo.width), "h":$(imageInfo.height)}';
//图片上传Token
//$imgName = 'preview/'.$qiniu->genRandomDir().'/'.Yii::$app->security->generateRandomString(20);
$imgPath = 'preview/'.$qiniu->generateRandomFilePath('$(ext)', 10);
$publicToken = $qiniu->getUploadToken('public', $imgPath, $returnBody);
$imgPath = 'preview/'.$qiniu->generateRandomFilePath('$(min)$(sec)$(ext)', 8);
$thumbToken = $qiniu->getUploadToken('public', $imgPath, $returnBody, 3600, true);
//视频上传Token
//$videoName = 'source/'.$qiniu->genRandomDir().'/'.Yii::$app->security->generateRandomString(20);
$videoName = 'source/'.$qiniu->generateRandomFilePath('$(ext)');
$videoToken = $qiniu->getUploadToken('video', $videoName, $returnBody);
$videoToken = $qiniu->getUploadToken('video', $videoName, $returnBody, 86400);
$model = new CoursePublishForm();
return $this->render('publish', compact('model', 'publicToken', 'videoToken'));
return $this->render('publish', compact('model', 'thumbToken', 'videoToken'));
}
}
<?php
/**
* Created by PhpStorm.
* User: pader
* Date: 16/10/8
* Time: 20:14
*/
namespace frontend\controllers;
use yii\helpers\Url;
class QiniuCallbackController extends \yii\web\Controller {
/**
* 上传回调 - 记录上传的文件
*
* 记录文件关关联处理以防止生成垃圾文件浪费空间
*/
public function actionRemUpload()
{
/* @var \Qiniu\Auth $auth */
$auth = \Yii::$app->qiniu->getAuthInstance();
//验证回调请求
$requestBody = file_get_contents('php://input');
$authorization = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
$currentUrl = \Yii::$app->request->hostInfo.\Yii::$app->request->getUrl();
if ($auth->verifyCallback($_SERVER['CONTENT_TYPE'], $authorization, $currentUrl, $requestBody)) {
echo 'ok';
} else {
echo 'no';
}
}
}
\ No newline at end of file
......@@ -19,7 +19,7 @@ AppAsset::addScript($this, '@web/assets/course_publish.js');
<form method="post" name="coursePublish">
<div class="cls-part">
<div class="tit">标题</div>
<input type="text" class="input-r-control" placeholder="请输入课程标题,20 个汉字以内...">
<input type="text" name="name" class="input-r-control" placeholder="请输入课程标题,20 个汉字以内...">
</div>
<div class="cls-part teacher-list">
......@@ -27,19 +27,19 @@ AppAsset::addScript($this, '@web/assets/course_publish.js');
<div class="checkbox">
<label>
<input type="checkbox">杨佩佩
<input name="teacher[]" type="checkbox">杨佩佩
</label>
<label class="m-l-10">
<input type="checkbox">马骏
<input name="teacher[]" type="checkbox">马骏
</label>
<label class="m-l-10">
<input type="checkbox">花木兰
<input name="teacher[]" type="checkbox">花木兰
</label>
<label class="m-l-10">
<input type="checkbox">张海
<input name="teacher[]" type="checkbox">张海
</label>
<span class="m-l-10"><a href="#">+ 添加讲师</a></span>
......@@ -57,43 +57,40 @@ AppAsset::addScript($this, '@web/assets/course_publish.js');
<div class="checkbox rules-set fl">
<label class="clearfix">
<input type="checkbox" class="fl"><span>会员价</span> <input type="text" class="input-r-control"> <span>元</span>
<input name="vip_price" type="checkbox" class="fl" value="1"><span>会员价</span> <input type="text" value="price" class="input-r-control"> <span>元</span>
</label>
</div>
<div class="checkbox rules-set m-l-20 fl">
<label class="clearfix">
<input type="checkbox" class="fl"><span>免费试看</span> <input type="text" class="input-r-control"> <span>分钟</span>
<input name="free_time" type="checkbox" class="fl"><span>免费试看</span> <input type="text" class="input-r-control"> <span>分钟</span>
</label>
</div>
</div>
</div>
<input type="hidden" name="vkey" value="{{videoKey}}" />
<input type="hidden" name="preview_pic" value="{{previewKey}}" />
<div class="cls-part">
<div class="tit">课程介绍</div>
<div class="cls-intro-textarea">
<textarea name="" id="" class="input-r-control" placeholder="请输入课程介绍..."></textarea>
<textarea name="intro" class="input-r-control" placeholder="请输入课程介绍..."></textarea>
</div>
</div>
<div class="cls-part">
<div class="tit">缩略图 <small>建议尺寸:900像素 * 500像素</small></div>
<div class="upload-video-screen">
<input type="file">
<i class="icon-image"></i>上传缩略图
</div>
<thumb-upload uptoken="<?=$thumbToken?>"></thumb-upload>
</div>
<div class="cls-part p-b-20">
<div class="tit">课程属性</div>
<div class="checkbox">
<label>
<input type="checkbox">推荐课程
</label>
</div>
</div>
<div class="btn-box text-center" style="border-top: 1px solid #e7e7e7; margin-top: 10px; ">
......@@ -101,6 +98,4 @@ AppAsset::addScript($this, '@web/assets/course_publish.js');
<button class="btn btn-save m-l-10">保存</button>
</div>
</form>
</div>
<input type="hidden" value="<?=$publicToken?>" id="previewToken"/>
<input type="hidden" value="<?=$videoToken?>" id="videoToken"/>
\ No newline at end of file
</div>
\ No newline at end of file
<template xmlns:v-bind="http://www.w3.org/1999/xhtml">
<div class="upload-video-screen" v-bind:id="uploaderId">
<i class="icon-image"></i>{{text}}
</div>
</template>
<style>
.upload-video-screen {cursor:pointer; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; padding:0 10px;}
</style>
<script>
import layer from "layer-js";
import str from "../../utils/string";
var defaultText = "上传缩略图";
export default{
data() {
return {
uploaderId: "thumbUploader" + str.rand(10),
state: "ready",
text: ""
}
},
props: {
uptoken: String
},
ready() {
this.text = defaultText;
var self = this;
require.ensure(["../../utils/qiniu"], function() {
var qiniu = require("../../utils/qiniu");
var uploader = new qiniu.Uploader({
browse_button: self.uploaderId,
drop_element: self.uploaderId,
upload_token: self.uptoken,
filters: {
max_file_size: '5mb',
mime_types: [
{title: "图片文件", extensions:"jpg,jpeg,gif,png"}
]
},
flash_swf_url: __CDN_URL__ + 'assets/plupload/Moxie.swf',
dragdrop: true,
multi_selection: false,
auto_start: true,
init: {
'FilesAdded': function(up, files) {
plupload.each(files, function(file) {
// self.videoSize = filesize(file.origSize, {fixed:2, spacer:' '}).human('si');
// self.videoName = file.name;
});
self.state = 'uploading';
up.start();
self.text = "上传中..";
},
//每个文件上传前
'BeforeUpload': function(up, file) {
},
'UploadProgress': function(up, file) {
self.text = "上传中.." + file.percent + "%";
},
//每个文件上传成功后
'FileUploaded': function(up, file, info) {
self.text = "上传完成";
setTimeout(function() {
self.text = file.name;
}, 1000);
var response = $.parseJSON(info.response);
self.$dispatch("thumb-uploaded", file.name, response);
},
'Error': function(up, err) {
var msg = "";
if (err.response) {
var data = $.parseJSON(err.response);
msg += "<br>" + data.error;
}
layer.alert("图片 " + err.file.name + " 上传失败!" + msg, {icon:5, title:"上传失败"});
self.state = "error";
},
//队列文件处理完毕后
'UploadComplete': function() {
self.state = 'completed';
}
}
});
//上传中禁止重选文件
self.$watch("state", function(val, old) {
if (val == "uploading") {
uploader.disableBrowse();
} else {
uploader.disableBrowse(false);
}
self.$dispatch("thumb-upload-state-change", val, old);
});
uploader.init();
});
}
}
</script>
<template>
<template xmlns:v-bind="http://www.w3.org/1999/xhtml">
<div>
<div class="upload-video-btn" id="uploadVideo1">
<input type="file">
<div class="upload-video-btn" v-bind:id="uploaderId" v-show="state=='ready' || state=='error'">
<i class="icon-play"></i>
<b>上传视频</b>
</div>
<div class="upload-ready" style="display:none;">
<h3></h3>
<div class="upload-ready" v-else>
<h3>{{videoName}}</h3>
<div class="video-detail">
视频大小:<span class="upload-info-size"></span>
速度:<span class="upload-info-speed"></span>
视频大小:{{videoSize}}
速度:{{speed}}
</div>
<div class="video-loading-text clearfix">
<div class="upload pull-left">已上传 <span class="upload-info-progress"></span>%</div>
<div class="time pull-right">大约还剩 <span class="upload-info-remain"></span></div>
<div class="upload pull-left">已上传 {{progress}}%</div>
<div class="time pull-right">大约还剩 <span class="upload-info-remain">{{remain}}</span></div>
</div>
<i class="upload-progress" style="width:0%;"></i>
<i class="upload-progress" v-bind:style="{width:progress + '%'}"></i>
</div>
</div>
</template>
<style>
.upload-ready {position:relative;}
.upload-video-btn {cursor:pointer;}
.upload-ready {position:relative; z-index:2;}
.upload-ready h3 {overflow:hidden; white-space:nowrap; text-overflow:ellipsis;}
</style>
<script>
import filesize from "file-size";
import layer from "layer-js";
import str from "../../utils/string";
export default {
// data() {
// return {
// msg:'hello vue'
// }
// },
data() {
return {
state: "ready",
videoName: "",
videoSize: "",
progress: 0,
speed: "",
uploaderId: "videoUploader" + str.rand(10)
}
},
props: {
uptoken: String
},
components:{
// 'other-component':OtherComponent,
// HeaderComponent,
},
ready() {
// if (typeof plupload == "undefined") {
// var err = "video-upload component required plupload!\nyou must add to asset by you self.";
// alert(err);
// console.log(err);
// return;
// }
var container = $(this.$el),
btn = container.find(".upload-video-btn"),
ready = container.find(".upload-ready");
var progress = ready.find(".upload-progress"),
infoProgress = ready.find(".upload-info-progress"),
infoRemain = ready.find(".upload-info-remain"),
infoSpeed = ready.find(".upload-info-speed");
var infoRemain = ready.find(".upload-info-remain");
var self = this,
startTime;
......@@ -81,10 +75,15 @@ export default {
});
var uploader = new qiniu.Uploader({
browse_button: 'uploadVideo1',
drop_element: 'uploadVideo1',
browse_button: self.uploaderId,
drop_element: self.uploaderId,
upload_token: self.uptoken,
max_file_size: '2gb',
filters: {
max_file_size: '2gb',
mime_types: [
{title: "视频文件", extensions:"3gp,flv,rm,rmvb,divx,mpg,mpeg,mp4,m4v,mov,mkv,vob,qt,avi,asf,asx,wmv,webm"}
]
},
flash_swf_url: __CDN_URL__ + 'assets/plupload/Moxie.swf',
dragdrop: true,
multi_selection: false,
......@@ -92,25 +91,23 @@ export default {
init: {
'FilesAdded': function(up, files) {
plupload.each(files, function(file) {
ready.find(".upload-info-size").text(filesize(file.origSize, {fixed:2, spacer:' '}).human('si'));
ready.find("h3").text(file.name);
self.videoSize = filesize(file.origSize, {fixed:2, spacer:' '}).human('si');
self.videoName = file.name;
});
container.find(".upload-video-btn").hide();
ready.show();
// container.find(".upload-video-btn").hide();
// ready.show();
self.state = 'uploading';
up.start();
up.disableBrowse();
startTime = (new Date()).getTime();
},
//每个文件上传前
'BeforeUpload': function(up, file) {
// 每个文件上传前,处理相关的事情
},
'UploadProgress': function(up, file) {
progress.css("width", file.percent + "%");
infoProgress.text(file.percent);
infoSpeed.text(filesize(up.total.bytesPerSec).human('si'));
self.progress = file.percent;
self.speed = filesize(up.total.bytesPerSec).human('si');
// var avgSpeed = file.loaded / (((new Date()).getTime() - startTime) / 1000);
......@@ -124,29 +121,44 @@ export default {
// infoProgress.text(file.percent);
// $("#" + file.id + " .attachup-list-element-status").html("上传中 - " + file.percent + "%");
},
//每个文件上传成功后
'FileUploaded': function(up, file, info) {
infoRemain.parent().text("上传完成");
infoSpeed.text("");
// 每个文件上传成功后,处理相关的事情
// 其中info是文件上传成功后,服务端返回的json,形式如:
// {
// "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
// "key": "gogopher.jpg"
// }
// 查看简单反馈
// var domain = up.getOption('domain');
// var res = parseJSON(info);
// var sourceLink = domain + res.key; 获取上传成功后的文件的Url
self.speed = "-/";
var response = $.parseJSON(info.response);
self.$dispatch("video-uploaded", file.name, response);
},
'Error': function(up, err, errTip) {
//上传出错时,处理相关的事情
'Error': function(up, err) {
var msg = "";
if (err.response) {
var data = $.parseJSON(err.response);
msg += "<br>" + data.error;
}
layer.alert("视频 " + err.file.name + " 上传失败!" + msg, {icon:5, title:"上传失败"});
self.state = "error";
},
//队列文件处理完毕后
'UploadComplete': function() {
//队列文件处理完毕后,处理相关的事情
self.state = 'completed';
}
}
});
//状态变化时禁用或启用上传按钮
self.$watch("state", function(val, old) {
if (val == "ready" || val == "error") {
uploader.disableBrowse(false);
} else {
uploader.disableBrowse();
}
self.$dispatch("video-upload-state-change", val, old);
});
uploader.init();
});
}
......
/**
* Created by pader on 16/9/28.
*/
var Vue = require('vue');
var videoUpload = require('../components/common/video-upload.vue');
var thumbUpload = require('../components/common/thumb-upload.vue');
var form = document.forms["coursePublish"];
var prvToken = $("#previewToken").val();
var vodToken = $("#videoToken").val();
var vm = new Vue({
el: '#publishMain',
data: {
videoKey: "",
previewKey: ""
},
components: {
videoUpload: videoUpload
videoUpload: videoUpload,
thumbUpload: thumbUpload
},
ready: function() {
var self = this;
this.$on("video-uploaded", function(name, data) {
self.videoKey = data.key;
});
this.$on("thumb-uploaded", function(name, data) {
self.previewKey = data.key;
});
}
});
require.ensure("jquery-validation", function() {
require('jquery-validation');
$(form).validate();
$(form).validate({
debug: true,
rules: {
required: true
}
});
});
/**
* Created by pader on 16/10/8.
*/
module.exports = {
/**
* 简单的生成一段随机字符串
*
* @param {int} len 字符串长度
* @returns {string}
*/
rand: function(len) {
var x="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",tmp="";
for(var i=0;i<len;i++){tmp+=x.charAt(Math.ceil(Math.random()*100000000)%x.length);}
return tmp;
}
};
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment