上传视频到服务器
1.引入js插件:
<script type="text/javascript" src="{{ static_url('plupload/js/plupload.full.min.js') }}"></script>
2.
html页面如图:
<script>
<label>上传视频:</label>
<input type="text" name="video_url" id="video_url" style="display: none">
<button class="btn new_btn-w-m btn-primary" href="#" id="video_upload_btn">上传视频
<span id="Progress" style=" opacity: 0.6;z-index:10; position: absolute; bottom: 0; left: 0; height: 100%; width: 0%; display: block; background-color: #003399"></span>
</button>
<span class="color-gray">支持AVI、wma、rmvb、rm、flash、mp4、mid、3GP等格式</span>
<video controls='controls' style="margin-top: 10px;max-width: 400px;width: 100%;">
<source src="" type='video/mp4' id="video">
</video>
<p class="showInfo"></p>
</script>
3.js代码
<script>
$(function () {
var uploader_video = new plupload.Uploader({//创建实例的构造方法
runtimes: 'gears,html5,html4,silverlight,flash', //上传插件初始化选用那种方式的优先级顺序
browse_button: ['video_upload_btn'], // 上传按钮
url: "/ajax/upload_video?path=videos", //远程上传地址
// flash_swf_url: 'js/plugins/plupload/Moxie.swf', //flash文件地址
// silverlight_xap_url: 'js/plugins/plupload/Moxie.xap', //silverlight文件地址
filters: {
max_file_size: '1gb', //最大上传文件大小(格式100b, 10kb, 10mb, 1gb)
mime_types: [//允许文件上传类型
{title: "files", extensions: "mpg,m4v,mp4,flv,3gp,mov,avi,rmvb,mkv,wmv"}
]
},
multipart_params: {
'_xsrf': $("input[name='_xsrf']").val()
},
chunk_size: "50mb", //分片上传文件时,每片文件被切割成的大小,为数字时单位为字节。也可以使用一个带单位的字符串,如"200kb"。当该值为0时表示不使用分片上传功能
multi_selection: false, //true:ctrl多文件上传, false 单文件上传
init: {
FilesAdded: function(up, files) { //文件上传前
plupload.each(files, function (file1) {
uploader_video.start();
});
},
UploadProgress: function(up, file) { //上传中,显示进度条
$('#Progress').css('width', file.percent+'%');
},
FileUploaded: function(up, file, info) { //文件上传成功的时候触发
var base = '/static/media/videos/';
var response = $.parseJSON(info.response);
if (response.status == 'ok') {
var url = "http://"+location.host+base + response.name;
$("#video").show().attr("src", url);
// console.log($("#video").parent());
$("#video").parent().get(0).load();
$("#video_url").val(url);
}
else {
alert(response.error);
}
},
Error: function(up, errObject) { //上传出错的时候触发
alert(errObject.code+errObject.message);
}
}
});
uploader_video.init();
});
</script>
后端代码
1.url路由
(r"/ajax/upload_video", UploadVideoFile),
2.python代码
class UploadVideoFile(BaseHandler):
def post(self):
path = self.get_argument("path")
input_name = self.get_argument("iname", "")
nums = self.get_argument("chunks", "")
num = self.get_argument("chunk", "")
# 视频文件名
filename = self.get_argument("name", "")
# 得到视频的存储路径upload_path,就是视频文件在哪个文件夹下面
upload_path = os.path.join(self.settings['upload_path'], path)
print path, nums, num, filename, upload_path
# 视频保存路径+视频文件名
filepath = os.path.join(upload_path, filename)
# 若不存在此目录,则创建之
if not os.path.isdir(upload_path):
# upload_path = upload_path.replace("/", "\\") #windows platform
os.makedirs(upload_path)
file_metas = self.request.files.get('file', [])
# filename = ''
try:
for meta in file_metas:
filename = meta['filename']
print filename
# 下面注释的地方不分片时需要用到,分片时用不到
# ext = os.path.splitext(filename)[1]
# 生成随机文件名
# filename = str(uuid.uuid4())
# filename = '%s%s' % (filename, ext)
# filepath = os.path.join(upload_path, filename)
# filepath = os.path.join(upload_path, num)
with open(filepath, 'ab') as up:
up.write(meta['body'])
except Exception as e:
print e
return self.write(json.dumps({"status": 'error', "msg": u"视频文件上传失败,请重新上传"}))
else:
print json.dumps({"status": 'ok', "msg": "", "base_url": "", "name": filename})
return self.write(json.dumps({"status": 'ok', "msg": "", "base_url": "", "name": filename}))
发送Ajax到后台,把视频或图片保存到数据库(保存的是地址)
1.ajax代码:
$('.btn.btn-white.add_content').click(function () {
if ($('#poster').attr('src') == '') {
alert('您还未上传内容照片!');
return false;
}
if ($('#title').val() == '') {
alert("内容标题不能为空!");
return false;
}
var xjson = {
"title": $("#title").val(),
"brief": $("#brief").val(),
"videourl" : $("#video_url").val(),
"image": $("#image_url").val(),
// "content": window.editor.html(),
"content": ue.getContentTxt(),
"category": $("#category").val(),
"tag" : $("#tag").val(),
'_xsrf': $("input[name='_xsrf']").val(),
};
$.ajax({
url: '/admin/study/recommend/add',
type: 'post',
data: xjson,
success: function (data) {
var jsons = jQuery.parseJSON(data);
alert(jsons.msg);
if (jsons.status == "ok") {
location.reload();
}
},
error: function () {
alert('error');
}
});
});
2.后代保存代码
class AdminAddStudyRecommend(BaseHandler):
"""增加学习推荐"""
@BaseHandler.admin_authed
def post(self):
datas = self.request.arguments
print "Add recommend=>",datas
info = dict()
last = self.db.tb_study_recommend.find_one({},{"id":1,"_id":0},sort=[("id", pymongo.DESCENDING)])
info['id'] = int(last.get("id",0)) + 1 if last else 1
info['title'] = self.get_argument('title')
info['brief'] = self.get_argument('brief')
info['img'] = self.get_argument('image')
info['content'] = self.get_argument('content')
info['category'] = self.get_argument('category')
info['tag'] = self.get_argument('tag',info.get('category'))
info['status'] = 1
for k, v in info.iteritems():
if not v:
return self.write(json.dumps({"status": 'error', "msg": k + "为必选项,请输入信息!"}))
info["videourl"] = self.get_argument('videourl',"")
info['userid'] = self.admin['userid']
info['atime'] = time.strftime("%Y-%m-%d %H:%M:%S")
self.db.tb_study_recommend.insert(info)
return self.write(json.dumps({"status": "ok", "msg": u'增加推荐内容成功'}))