OSS網頁上傳和斷點續傳(終結篇)

yuejin發表於2018-09-18

有了之前OSS網頁上傳和斷點續傳(OSS配置篇)和(STSToken篇),其萬事俱備只欠東風啦,此終結篇即將展示OSS上傳檔案及斷點續傳的無限魅力...

網路卡頓、延遲能續傳嗎?能!

關了瀏覽器,還能續傳嗎?能!!

關了電腦,還能續傳嗎?能!!!

關了電腦、跑到異地去,還能續傳嗎?能!!!!

這麼屌?就是這麼屌!下面就看看是不是這麼屌!

1、下載OSS的BrowserJS-SDK檔案aliyun-oss-sdk-5.2.0.min.js,在此引用5.2.0版本

下載地址:https://github.com/ali-sdk/ali-oss/tree/release/5.2.0

引用aliyun-oss-sdk-5.2.0.min.js和jquery檔案即可

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Res/aliyun-upload-sdk-1.4.0/aliyun-oss-sdk-5.2.0.min.js"></script>

2、HTML程式碼

    <div id="up_wrap"></div>
    <div class="form-group">
        <input type="file" id="file" multiple="multiple" />
    </div>
    <div class="form-group">
        <input type="button" class="btn btn-primary" id="file-button" value="Upload" />
        <input type="button" class="btn btn-primary" id="Continue-button" value="Continue" />
    </div>

3、檔案上傳和斷點續傳程式碼

<script type="text/javascript">
        var appServer = 'http://localhost:87/STS/Token';
        var bucket = 'cactus-open';
        var region = 'oss-cn-hangzhou';
        var uid = 'x';//使用者標識
        var urllib = OSS.urllib;
        var Buffer = OSS.Buffer;
        var OSS = OSS.Wrapper;
        //獲取授權STSToken,並初始化client
        var applyTokenDo = function (func) {
            var url = appServer;
            return urllib.request(url, {
                method: 'GET'
            }).then(function (result) {
                var creds = JSON.parse(result.data);
                var client = new OSS({
                    region: region,
                    accessKeyId: creds.AccessKeyId,
                    accessKeySecret: creds.AccessKeySecret,
                    stsToken: creds.SecurityToken,
                    bucket: bucket
                });
                return func(client);
            });
        };
        //上傳檔案
        var uploadFile = function (client) {
            if (upfiles.length < 1)
                return;
            upfile = upfiles[0];
            var file = upfile.file;
            var key = upfile.name;
            var objkey = key + "_" + uid + ".json";
            return client.multipartUpload(key, file, {
                progress: function (p, cpt, res) {
                    console.log("p:", p);
                    console.log("cpt:", cpt);
                    if (cpt != undefined) {
                        var content = JSON.stringify(cpt);
                        client.put(objkey, new Buffer(content));
                    }
                    return function (done) {
                        var bar = document.getElementById('progress-bar_' + upfile.num);
                        bar.style.width = Math.floor(p * 100) + '%';
                        bar.innerHTML = Math.floor(p * 100) + '%';
                        done();
                    }
                }
            }).then(function (res) {
                console.log('upload success: ', res);
                upfiles.shift();
                client.delete(objkey);                
                applyTokenDo(uploadFile);
            });
        };
        //斷點續傳檔案
        var reUploadFile = function (client) {
            if (upfiles.length < 1)
                return;
            upfile = upfiles[0];
            var file = upfile.file;
            var key = upfile.name;
            var objkey = key + "_" + uid + ".json";
            return client.get(objkey).then(function (res) {
                var data = JSON.parse(res.content);
                data.file = file;
                return client.multipartUpload(key, file, {
                    checkpoint: data,
                    progress: function (p, cpt, res) {
                        console.log("p:", p);
                        console.log("cpt:", cpt);
                        if (cpt != undefined) {
                            var content = JSON.stringify(cpt);
                            store.put(objkey, new Buffer(content));
                        }
                        return function (done) {
                            var bar = document.getElementById('progress-bar_' + upfile.num);
                            bar.style.width = Math.floor(p * 100) + '%';
                            bar.innerHTML = Math.floor(p * 100) + '%';
                            done();
                        }
                    }
                }).then(function (ret) {
                    console.log('upload success:', ret);
                    upfiles.shift();
                    client.delete(objkey);                    
                    applyTokenDo(uploadFile);
                });
            });
        };
        //檔案上傳佇列
        var upfiles = [];

        $(function () {
            //初始化檔案上傳佇列
            $("#file").change(function (e) {
                var ufiles = $(this).prop('files');
                var htm = "";
                for (var i = 0; i < ufiles.length; i++) {
                    htm += "<dl><dt>" + ufiles[i].name + "</dt><dd><div class=\"progress\"><div id=\"progress-bar_" + i + "\" class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"min-width: 2em;\">0%</div></div></dd></dl>";
                    upfiles.push({
                        num: i,
                        name: ufiles[i].name,
                        file: ufiles[i]
                    })
                }
                console.log('upfiles:', upfiles);
                $("#up_wrap").html(htm);
            })
            //上傳
            $("#file-button").click(function () {
                applyTokenDo(uploadFile);
            })
            //續傳
            $("#Continue-button").click(function () {
                applyTokenDo(reUploadFile);
            })
        })
    </script>

^_^^_^!程式碼這麼少,效果這麼好,原來這麼屌!上圖:

單個檔案、多個檔案,小檔案、大檔案,隨便來!!

原理很簡單,把上傳斷點儲存在OSS中,不管怎麼斷網、關瀏覽器、關電腦.....。統統不管,都能上傳。當上傳完畢後,會自動刪掉儲存斷點的檔案。

 

相關文章