Commit 9b3e9df1 authored by 杨培's avatar 杨培

编辑器图片上传功能

附件由本地服务器中转上传功能
我的课程数据验证
上传池类方法参数调整
布局调整
其它各种调整
parent 448ab98c
......@@ -42,6 +42,25 @@ class Utils
];
}
/**
* 将 $model->errors 中的错误组织成一维数组返回
*
* @param array $errors
* @return array
*/
public static function fetchErrors($errors)
{
$msgs = [];
foreach ($errors as $k => $v) {
foreach ($v as $msg) {
$msg[] = $msg;
}
}
return $msgs;
}
/**
* 生成4-6位随机数
* @param int $length
......
......@@ -8,16 +8,26 @@
namespace common\models;
use Qiniu\Storage\UploadManager;
use Yii;
use yii\base\Model;
class AttachUploadForm extends Model
{
const SESS_PREFIX = 'attachpool_';
/**
* @var \yii\web\UploadedFile
*/
public $file;
/**
* 用来保存已上传文件列表的session临时标记
* @var string
*/
public $tmp;
public function formName() {
return '';
}
......@@ -29,23 +39,89 @@ class AttachUploadForm extends Model
return [
['file', 'image', 'skipOnEmpty' => false, 'extensions' => ['png', 'jpg', 'jpeg', 'gif'],
'maxSize'=>$mb * 5, 'minWidth'=>1, 'minHeight'=>1],
['tmp', 'required']
];
}
/**
* 上传文件
* 暂存到本地
*
* @return bool|string 上传成功返回文件路径,失败返回 false
*/
public function upload()
public function uploadTmp()
{
if ($this->validate()) {
//'uploads/' . $this->file->baseName . '.' . $this->file->extension
$tmp = tempnam('yunya', 'attach').'.'.$this->file->extension;
return $this->file->saveAs($tmp) ? $tmp : false;
} else {
}
return false;
}
/**
* 上传到七牛云
*
* @param string $storage
* @param string $dir
* @return array|bool
* @throws \Exception
*/
public function uploadStorage($storage='public', $dir='content')
{
$result = $this->uploadTmp();
if ($result === false) {
return false;
}
//上传到七牛
/* @var \common\components\Qiniu $qiniu */
$qiniu = Yii::$app->qiniu;
$uploadMgr = new UploadManager();
$key = $dir.'/' . $qiniu->generateRandomFilePath('$(ext)');
$token = $qiniu->getUploadToken($storage, $key);
list($ret, $err) = $uploadMgr->putFile($token, null, $result);
unlink($result); //删除本地临时文件
if ($err !== null) {
$this->addError('file', $err->message());
return false;
} else {
//存储到 session 中记录
$session = Yii::$app->session;
$key = self::SESS_PREFIX.$this->tmp;
$pool = $session->get($key);
if ($pool === null) {
$pool = [];
}
$pool[] = $ret['uuid'];
$session->set($key, $pool);
return $ret;
}
}
/**
* 从临时标记中获取上传的附件uuid列表
*
* @param string $tmp
* @return array|null
*/
public static function getTmpAttachs($tmp)
{
$key = self::SESS_PREFIX.$tmp;
return Yii::$app->session->get($key);
}
public static function clearTmpAttachs($tmp)
{
$key = self::SESS_PREFIX.$tmp;
return Yii::$app->session->remove($key);
}
}
\ No newline at end of file
......@@ -68,5 +68,28 @@ class ClassesTeacher extends \yii\db\ActiveRecord
return $obj->select('t.id,t.user_id,t.name,t.avatar')->join('LEFT JOIN', $teacherTable.' t', 't.id=c.teacher_id')
->from(self::tableName().' c')->where(['c.class_id'=>$classId])->asArray()->all();
}
/**
* 过滤出课堂拥有的讲师ID列表
*
* @param int $classId
* @param array $teacherIds
* @return array
*/
public static function filterOwnTeacherIds($classId, $teacherIds)
{
$query = self::find();
$result = $query->select('teacher_id')->where(['class_id'=>$classId, 'teacher_id'=>$teacherIds])->all();
$ids = [];
if ($result) {
foreach ($result as $row) {
$ids[] = $row->teacher_id;
}
}
return $ids;
}
}
......@@ -4,6 +4,7 @@ namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\HtmlPurifier;
use yii\redis\ActiveRecord;
/**
......@@ -12,8 +13,8 @@ use yii\redis\ActiveRecord;
* @property integer $id
* @property integer $user_id
* @property integer $classed_id
* @property string $avatar
* @property string $name
* @property array $teacher
* @property integer $price
* @property integer $free_time
* @property string $intro
......@@ -25,12 +26,24 @@ use yii\redis\ActiveRecord;
*/
class Course extends \yii\db\ActiveRecord
{
public function formName() {
return '';
}
/**
* @inheritdoc
*/
public static function tableName()
public function beforeSave($insert)
{
return 'course';
if (!parent::beforeSave($insert)) {
return false;
}
$this->name = strip_tags($this->name);
$this->intro = HtmlPurifier::process($this->intro);
return true;
}
/**
......@@ -44,10 +57,9 @@ class Course extends \yii\db\ActiveRecord
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
// if you're using datetime instead of UNIX timestamp:
// 'value' => new Expression('NOW()'),
],];
]
]
];
}
/**
......@@ -56,11 +68,15 @@ class Course extends \yii\db\ActiveRecord
public function rules()
{
return [
[['user_id', 'classed_id', 'avatar', 'name', 'price', 'free_time', 'intro', 'preview_pic'], 'required'],
[['user_id', 'classed_id', 'price', 'free_time', 'recommend', 'status', 'created_at', 'updated_at'], 'integer'],
[['intro'], 'string'],
[['avatar', 'preview_pic'], 'string', 'max' => 255],
[['name'], 'string', 'max' => 32],
[['name', 'preview_pic'], 'required'],
['name', 'string', 'length'=>[1,60]],
//['teacher', 'exist', 'targetAttribute'=>'teacher_id', 'targetClass'=>CourseTeacher::className(), 'allowArray'=>true],
['user_id', 'integer'],
['class_id', 'integer'],
['price', 'integer', 'min'=>0, 'max'=>9999],
['free_time', 'integer', 'min'=>0, 'max'=>15],
['recommend', 'boolean'],
['status', 'in', 'range'=>[0, 1, 2, 3]]
];
}
......@@ -70,19 +86,12 @@ class Course extends \yii\db\ActiveRecord
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'classed_id' => 'Classed ID',
'avatar' => 'Avatar',
'name' => 'Name',
'price' => 'Price',
'free_time' => 'Free Time',
'intro' => 'Intro',
'preview_pic' => 'Preview Pic',
'recommend' => '0 表示推荐 1推荐',
'status' => '0 未审核 1 审核通过 2 审核不通过 3 锁定 ',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'teacher' => '讲师',
'name' => '标题',
'price' => '价格',
'free_time' => '免费试看',
'intro' => '课程介绍',
'preview_pic' => '预览图'
];
}
......
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "course_teacher".
*
* @property integer $course_id
* @property integer $teacher_id
*/
class CourseTeacher extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'course_teacher';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['course_id', 'teacher_id'], 'required'],
[['course_id', 'teacher_id'], 'integer'],
];
}
}
......@@ -3,6 +3,8 @@
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
/**
* This is the model class for table "courseware".
......@@ -19,7 +21,7 @@ use Yii;
* @property integer $created_at
* @property integer $updated_at
*/
class Courseware extends \yii\db\ActiveRecord
class Courseware extends ActiveRecord
{
/**
* @inheritdoc
......@@ -28,6 +30,10 @@ class Courseware extends \yii\db\ActiveRecord
{
return 'courseware';
}
public function formName() {
return '';
}
/**
* @inheritdoc
......@@ -35,11 +41,10 @@ class Courseware extends \yii\db\ActiveRecord
public function rules()
{
return [
[['user_id', 'course_id', 'name', 'size', 'time', 'format', 'created_at', 'updated_at'], 'required'],
[['user_id', 'course_id', 'type', 'status', 'created_at', 'updated_at'], 'integer'],
[['user_id', 'course_id', 'name', 'size', 'time', 'format'], 'required'],
[['user_id', 'course_id', 'type', 'status', 'size', 'time'], 'integer'],
[['name'], 'string', 'max' => 128],
[['size', 'time'], 'string', 'max' => 32],
[['format'], 'string', 'max' => 16],
[['format'], 'string', 'max' => 16]
];
}
......@@ -63,6 +68,22 @@ class Courseware extends \yii\db\ActiveRecord
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
]
]
];
}
/**
* 根据id判断数据是否存在
* @param $id
......
......@@ -56,11 +56,14 @@ class UploadPools extends ActiveRecord
* 获取上传池中的文件
*
* @param string $uuid
* @param false $uuid 只获取未使用的文件
* @return array
*/
public static function getFileInfo($uuid)
public static function getFileInfo($uuid, $unused=true)
{
$file = self::findOne(['uuid'=>$uuid]);
$where = ['uuid'=>$uuid];
$unused && $where['status'] = self::STATUS_UNUSE;
$file = self::findOne($where);
if ($file) {
$file = $file->toArray();
......
<?php
namespace frontend\controllers;
use common\libs\Utils;
use common\models\AttachUploadForm;
use frontend\models\CoursePublishForm;
use Qiniu\Storage\UploadManager;
use common\models\ClassesTeacher;
use common\models\Course;
use common\models\CourseTeacher;
use common\models\Courseware;
use common\models\UploadPools;
use Qiniu\Storage\BucketManager;
use Yii;
use yii\web\Response;
use yii\web\UploadedFile;
......@@ -35,10 +40,80 @@ class MyCourseController extends \yii\web\Controller
//$videoName = 'source/'.$qiniu->genRandomDir().'/'.Yii::$app->security->generateRandomString(20);
$videoName = 'source/' . $qiniu->generateRandomFilePath('$(ext)');
$videoToken = $qiniu->getUploadToken('video', $videoName, 86400);
return $this->render('publish', compact('thumbToken', 'videoToken'));
}
public function actionSubmit()
{
$course = new Course();
$courseware = new Courseware();
$courseTeacher = new CourseTeacher();
$request = Yii::$app->request;
$userId = 1;
$classId = 1;
//课程数据
$courseData = [
'user_id' => $userId,
'classed_id' => $classId
];
foreach (['name', 'teacher', 'price', 'free_time', 'intro', 'preview_pic', 'recommend'] as $key) {
$courseData[$key] = $request->post($key);
}
$course->load($courseData);
if (!$course->validate()) {
Utils::ajaxResponse(false, join('<br>', Utils::fetchErrors($course->errors)));
return;
}
$model = new CoursePublishForm();
$uploadModel = new AttachUploadForm();
return $this->render('publish', compact('model', 'uploadModel', 'thumbToken', 'videoToken'));
//过滤已拥有的讲师列表
$teacherIds = $request->post('teacher', []);
$teacherIds = ClassesTeacher::filterOwnTeacherIds($classId, $teacherIds);
//课件数据
$vuid = $request->post('vuid');
$vuid = '2ade5751-8fae-11e6-a1b1-1242ac110005'; //测试uuid
$cwData = [
'user_id' => $userId,
'course_id' => 0,
'name' => $vuid, //视频的 uuid
'size' => 0,
'time' => 0,
'format' => ''
];
$video = UploadPools::getFileInfo($vuid);
if ($video) {
$bucket = Yii::$app->qiniu->getStorageConfig($video['storage'], 'bucket');
$auth = Yii::$app->qiniu->getAuthInstance();
$bucketMgr = new BucketManager($auth);
list($ret, $err) = $bucketMgr->stat($bucket, $video['key']);
if ($err !== null) {
echo $err->message();
} else {
print_r($ret);
}
}
return;
$courseware->load($cwData);
if ($courseware->validate()) {
echo 'Success';
} else {
print_r($courseware->errors);
}
}
/**
......@@ -58,36 +133,22 @@ class MyCourseController extends \yii\web\Controller
return ['success'=>false, 'msg'=>'请求方式错误'];
}
//$model->load(Yii::$app->request->post());
$model->file = UploadedFile::getInstance($model, 'file');
$result = $model->upload();
$model->tmp = Yii::$app->request->post('tmp');
$result = $model->uploadStorage();
if ($result === false) {
return ['success'=>false, 'msg'=>join('; ', $model->errors)];
}
//上传到七牛
/* @var \common\components\Qiniu $qiniu */
$qiniu = Yii::$app->qiniu;
$uploadMgr = new UploadManager();
$key = 'content/' . $qiniu->generateRandomFilePath('$(ext)');
$token = $qiniu->getUploadToken('public', $key);
list($ret, $err) = $uploadMgr->putFile($token, null, $result);
unlink($result); //删除本地临时文件
if ($err !== null) {
return ['success'=>false, 'msg'=>$err->message()];
} else {
return ['success'=>true, 'msg'=>'', 'file_path'=>$ret['src'], 'key'=>$ret['key'], 'uuid'=>$ret['uuid']];
return ['success'=>false, 'msg'=>$model->errors];
}
return ['success'=>true, 'msg'=>'', 'file_path'=>$result['src'], 'key'=>$result['key'], 'uuid'=>$result['uuid']];
}
public function actionTest()
{
return tempnam('yunya', 'attach').'.jpg';
$data = AttachUploadForm::getTmpAttachs('dxQ9tE6XyKX2TD6bndgP');
var_dump($data);
}
}
......@@ -5,11 +5,14 @@
* Date: 16/9/28
* Time: 17:43
*/
namespace frontend\models;
use common\models\CourseTeacher;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\HtmlPurifier;
class CoursePublishForm extends \yii\base\Model
class CoursePublishForm extends ActiveRecord
{
public $name;
......@@ -20,10 +23,69 @@ class CoursePublishForm extends \yii\base\Model
public $intro;
public $preview;
public $recommend;
public $status;
public $create_at;
public $update_at;
public function formName() {
return "";
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'name' => '标题',
'avatar' => 'Avatar',
'intro' => 'Intro',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
/**
* @inheritdoc
*/
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
$this->intro = HtmlPurifier::process($this->intro);
return true;
}
public function rules()
{
return [
[['name', 'video', 'preview'], 'required'],
['name', 'string', 'length'=>[1,60]],
['teacher', 'exist', 'targetAttribute'=>'teacher_id', 'targetClass'=>CourseTeacher::className(), 'allowArray'=>true],
['prirce', 'integer', 'min'=>0, 'max'=>9999],
['free_time', 'integer', 'min'=>0, 'max'=>15],
['recommend', 'boolean'],
['status', 'in', 'range'=>[0, 1, 2, 3]]
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
]
// if you're using datetime instead of UNIX timestamp:
// 'value' => new Expression('NOW()'),
]
];
}
......
......@@ -47,6 +47,7 @@ $(function() {
JS;
$this->registerJs($js, View::POS_END);
$this->registerCss('[v-cloak] {display:none;}');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
......
......@@ -6,62 +6,10 @@ use frontend\assets\AppAsset;
/* @var $this \yii\web\View */
/* @var $content string */
AppAsset::register($this);
AppAsset::addCss($this, '@web/assets/css/style.css');
//$assetsUrl = Yii::$app->assetManager->baseUrl.'/assets';
//
//$js = <<<JS
//var global = (function () {
// this.static_url = "$assetsUrl";
//})();
//JS;
//
//$this->registerJs($js, View::POS_HEAD);
$js = <<<JS
$(function() {
var Accordion = function(el, multiple) {
this.el = el || {};
this.multiple = multiple || false;
// Variables privadas
var links = this.el.find(".link");
// Evento
links.on("click", {el: this.el, multiple: this.multiple}, this.dropdown)
};
Accordion.prototype.dropdown = function(e) {
var el = e.data.el, self = $(this), next = self.next();
next.slideToggle();
self.parent().toggleClass("open");
if (!e.data.multiple) {
el.find(".submenu").not(next).slideUp().parent().removeClass("open");
}
};
new Accordion($("#accordion"), false);
});
JS;
$this->registerJs($js, View::POS_END);
$this->beginPage();
$this->beginBody();
$this->beginContent('@app/views/layouts/center.php');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= \Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title><?= $this->title ? Html::encode($this->title) . '-' : '' ?>最课堂</title>
<?= Html::csrfMetaTags() ?>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody(); ?>
<?php $this->beginContent('@app/views/layouts/center.php'); ?>
<div class="tp-sidebar">
<div class="logo"><a href="/"><img src="<?= Yii::$app->assetManager->baseUrl ?>/img/logo.png"></a></div>
......@@ -107,15 +55,7 @@ $this->registerJs($js, View::POS_END);
</div>
</div>
</div>
<?php $this->endContent(); ?>
<div class="foot navbar-fixed-bottom">
<p><a href="#">隐私权政策</a> - <a href="#">服务条款</a> - <a href="#">地图条款</a></p>
<p>©2016 Zuiketang.com</p>
</div>
<?php $this->endBody(); ?>
</body>
</html>
<?php $this->endPage(); ?>
<?php
$this->endContent();
$this->endBody();
$this->endPage();
......@@ -13,7 +13,6 @@ $this->title = '发布课程';
//AppAsset::addScript($this, '@web/assets/single-lib/plupload/plupload.full.min.js');
AppAsset::addScript($this, '@web/assets/course_publish.js');
AppAsset::addCss($this, '@web/assets/css/course_publish.css');
$this->registerCss('[v-cloak] {display:none;}');
?>
<div class="send-class" id="publishMain" xmlns:v-el="http://www.w3.org/1999/xhtml">
<div class="tit">发布课程</div>
......@@ -60,12 +59,8 @@ $this->registerCss('[v-cloak] {display:none;}');
</label>
</div>
</div>
</div>
<input type="hidden" name="vuid" value="{{vuid}}" />
<input type="hidden" name="preview_pic" value="{{previewKey}}" />
<input type="hidden" name="attachs" value="{{attachs}}" />
<div class="cls-part">
<div class="tit">课程介绍</div>
<div class="cls-intro-textarea">
......@@ -82,11 +77,15 @@ $this->registerCss('[v-cloak] {display:none;}');
<div class="tit">课程属性</div>
<div class="checkbox">
<label>
<input type="checkbox">推荐课程
<input type="checkbox" name="recommend">推荐课程
</label>
</div>
</div>
<input type="hidden" name="tmp" value="{{tmp}}" />
<input type="hidden" name="vuid" value="{{vuid}}" />
<input type="hidden" name="preview" value="{{previewKey}}" />
<div class="btn-box text-center" style="border-top: 1px solid #e7e7e7; margin-top: 10px; ">
<button class="btn btn-nobg">取消</button>
<button class="btn btn-save m-l-10">保存</button>
......
......@@ -7,6 +7,8 @@ var thumbUpload = require('../components/uploader/thumb-upload.vue');
var layer = require("layer-js");
var Simditor = require("../utils/simditor");
var str = require("../utils/string");
require('jquery-validation');
//$.ajaxSetup({
......@@ -27,7 +29,8 @@ var vm = new Vue({
teachers: [],
atState: 0,
addTeacherName: "",
checkedTeachers: []
checkedTeachers: [],
tmp: str.rand(20)
},
components: {
videoUpload: videoUpload,
......@@ -80,18 +83,75 @@ var vm = new Vue({
self.previewKey = data.key;
});
$(form).validate({
debug: true,
var validator = $(form).validate({
//debug: true,
//errorClass: "",
//validClass: "",
ignore: "",
rules: {
name: {
required: true
},
preview: {
required: true
},
vuid: {
required: true
}
},
messages: {
name: {
required: "请填写标题"
},
preview: {
required: "必须上传缩略图"
},
vuid: {
required: "您还没有上传视频"
}
},
errorPlacement: function(error, element) {
var text = error.text();
var org = element.get(0);
var to = null;
if (org == form.vuid) {
to = $(".upload-video-btn").get(0);
} else if (org == form.preview) {
to = $(".upload-video-screen").get(0);
} else {
to = org;
}
if (text) {
if (to.tipIndex) {
layer.close(to.tipIndex);
}
to.tipIndex = layer.tips(text, to, {
tips: 1,
time: 0,
tipsMore: true
});
} else if (to.tipIndex) {
layer.close(to.tipIndex);
to.tipIndex = null;
}
},
success: function() {}, //添加 success 后,当表单验证成功时才会触发 errorPlacement,否则验证成功不触发
submitHandler: function() {
var data = $(form).serialize();
$.post("/my-course/submit", data, function(t) {
alert(t);
});
return false;
}
});
var doValidate = function() { validator.form(); };
this.$watch("vuid", doValidate);
this.$watch("previewKey", doValidate);
var editor = new Simditor({
textarea: $("#introEditor"),
toolbarFloat: false,
......@@ -99,7 +159,8 @@ var vm = new Vue({
upload: {
url : '/my-course/upload', //文件上传的接口地址
params: {
"_csrf-frontend": $("meta[name='csrf-token']").attr("content")
"_csrf-frontend": $("meta[name='csrf-token']").attr("content"),
tmp: self.tmp
},
fileKey: 'file', //服务器端获取文件数据的参数名
connectionCount: 3,
......@@ -107,5 +168,4 @@ var vm = new Vue({
}
});
}
});
});
\ 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