1. 程式人生 > >前端上傳元件Plupload使用---上傳視訊

前端上傳元件Plupload使用---上傳視訊

上傳視訊到伺服器

1.引入js外掛:

<script type="text/javascript" src="{{ static_url('plupload/js/plupload.full.min.js') }}"></script>

2.html頁面如圖:

<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>

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: "5mb", //分片上傳檔案時,每片檔案被切割成的大小,為數字時單位為位元組。也可以使用一個帶單位的字串,如"200kb"。當該值為0時表示不使用分片上傳功能
        multi_selection: false, //true:ctrl多檔案上傳, false 單檔案上傳
        init: {
            FilesAdded: function(up, files) { //檔案上傳前
                plupload.each(files, function (file) {
                    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", "")
        # 得到視訊的儲存路徑upload_path,就是視訊檔案在哪個資料夾下面
        upload_path = os.path.join(self.settings['upload_path'], path)

        # print path,upload_path
        # 若不存在此目錄,則建立之
        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']
                ext = os.path.splitext(filename)[1]
                # 生成隨機檔名
                filename = str(uuid.uuid4())
                filename = '%s%s' % (filename, ext)
                filepath = os.path.join(upload_path, filename)
                with open(filepath, 'wb') 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}))