阿里oss文件上传 删除文件 js脚本

accessid = '';
accesskey = '';
host = '';
policyBase64 = '';
signature = '';
callbackbody = '';
filename = '';
key = '';
expire = 0;
g_object_name = '';
g_object_name_type = '';
now = timestamp = Date.parse(new Date()) / 1000;
file_cancer_id = '';

function send_request() {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        serverUrl = '/fileupload/alioss/getSnt.action'
        xmlhttp.open("GET", serverUrl, false);
        xmlhttp.send(null);
        //console.log(xmlhttp.responseText);
        return xmlhttp.responseText;
    }
    else {
        alert("您的浏览器不支持,建议使用谷歌浏览器");
    }
};


function delete_request(oldFile) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        deleteUrl = '/fileupload/alioss/deleteFile.action?fileUrl=' + oldFile;
        xmlhttp.open("GET", deleteUrl, false);
        xmlhttp.send(null);
        //console.log(xmlhttp.responseText);
        return xmlhttp.responseText;
    }
    else {
        alert("您的浏览器不支持,建议使用谷歌浏览器");
    }
};


function get_signature() {
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        body = send_request();
        var obj = eval("(" + body + ")");
        obj = obj["body"];
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {
    g_object_name = key + random_string(10) + suffix;
    return ''
}

function get_uploaded_object_name(filename) {
    return g_object_name + "" + filename;
}


function createObjectURL(object) {
    return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}

function set_upload_param(up, filename, ret) {
    if (ret == false) {
        ret = get_signature();
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename);
        calculate_object_name(filename);
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然,默认会返回204
        'callback': callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function video_upload_cancel(file_id) {  //取消上传
    uploader.stop();
    var obj_file = uploader.getFile(file_id);
    uploader.removeFile(obj_file);
    var $fileDelete = $("#" + file_id);
    $fileDelete.remove();
    document.getElementById('console').innerHTML = "";
    $("#video_upload_cancel").hide();
    $("#selectfiles").show();

    if ($("#fileName").val()) {
        var zipUrlInfo = '下载地址 <a target="_blank" href="' + $("#fileName").val() + '">点击这里</a>';
        $("#ossfile").html(zipUrlInfo);
    }
}


function video_upload_delete(file_id) {  //删除视频
    var obj_file = uploader.getFile(file_id.id);
    var fileName = host + get_uploaded_object_name(obj_file.name);
    uploader.removeFile(obj_file);
    var $fileDelete = $("#" + file_id.id);
    $fileDelete.remove();
    document.getElementById('console').innerHTML = "";
}


var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'selectfiles',
    multi_selection: false,
    container: document.getElementById('container'),
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',
    filters: {
        mime_types: [ //只允许上传的类型 ,分割
            {title: "zip files", extensions: "zip"}
        ],
        max_file_size: '200mb', //最大只能上传500mb的文件
        prevent_duplicates: true //不允许选取重复文件
    },

    init: {
        PostInit: function () {
            document.getElementById('ossfile').innerHTML = '';
            set_upload_param(uploader, '', false);
            document.getElementById('postfiles').onclick = function () {
                set_upload_param(uploader, '', false);
                return false;
            };

            document.getElementById('video_upload_cancel').onclick = function () {
                video_upload_cancel(file_cancer_id);
                return false;
            };
        },

        FilesAdded: function (up, files) {
            if (uploader.files.length > 1) {
                document.getElementById('console').innerHTML = "";
                document.getElementById('console').appendChild(document.createTextNode("\n只能上传一个文件"));
                uploader.removeFile(files[0]);
                return;
            }
            document.getElementById("ossfile").innerHTML = '';
            var upFileName = '';
            plupload.each(files, function (file) {
                document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">文件名' + file.name + '(' + plupload.formatSize(file.size) + ')<b></b>'
                    + '<div class="progress" style="margin-top: -8px; "><div class="progress-bar" style="width: 0%"></div></div>'
                    + '</div>';
                upFileName = file.name;
                file_cancer_id = file.id;
            });
            //set_upload_param(up, upFileName, true);
            $("#video_upload_cancel").show();
            $("#selectfiles").hide();
        },

        BeforeUpload: function (up, file) {
            set_upload_param(up, file.name, true);
        },

        UploadProgress: function (up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            progBar.style.width = 2 * file.percent + 'px';
            progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function (up, file, info) {
            if (info.status == 200) {
                var downUrl = host + "/" + g_object_name;
                document.getElementById("ossfile").innerHTML = '上传成功,下载地址 <a target="_blank" href="' + downUrl + '">点击这里</a>';
                uploader.removeFile(file);
                document.getElementById('console').innerHTML = "";
                $("#video_upload_cancel").hide();
                $("#selectfiles").show();
                //调用video/upload.js的上传方法
                var oldFile = $("#fileName").val();
                $("#fileName").val(downUrl);
                //console.log("上传路径:" + downUrl);
                //上传完之后 应该删除旧的数据
                if (oldFile) {
                    delete_request(oldFile);
                }
                //执行保存
                var inputNode = document.getElementById('savebtn');
                var evt = new MouseEvent("click", {
                    bubbles: false, cancelable: true, view: window
                });
                inputNode.dispatchEvent(evt);
            }
            else {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            }
        },

        Error: function (up, err) {
            document.getElementById('console').innerHTML = "";
            if (err.code == -600) {
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件不能超过200mb"));
            }
            else if (err.code == -601) {
                document.getElementById('console').appendChild(document.createTextNode("\n请选择后缀是zip的文件"));
            }
            else if (err.code == -602) {
                document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经选择了,请先上传或取消上传该文件"));
            }
            else {
                document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
            }
        }
    }
});

uploader.init();



<div class="advert_file" style="top: 6px; right: 4%;">
                               <div id="container" style="position: relative;">
                                   <button id="selectfiles"  class="btn btn-primary btn-font input-btn" style="position: relative; z-index: 1; margin: 0 20px;">上传</button>
                                   <button id="postfiles" style="display:none;position: relative; z-index: 1;" class="btn btn-primary btn-font input-btn">开始</button>
                                   <button  id="video_upload_cancel" class="btn btn-primary btn-font input-btn" style="display:none;position: relative; z-index: 1; margin: 0 20px;">取消</button>
                                   <div id="html5_1c0o864eg1las1t11nonup31bnf3_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 0px; left: 0px; width: 82px; height: 34px; overflow: hidden; z-index: 0;">
                                       <input id="html5_1c0o864eg1las1t11nonup31bnf3" type="file" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;" multiple="" accept="application/zip">
                                   </div>
                               </div>
                               <input style="display:none;" id="fileName" name="fileName" type="text" ng-model="dataInfo.zip" style="width:350px;height:30px" disabled/>&nbsp;&nbsp;&nbsp;&nbsp;
                               <input style="display:none;" id="fileTime" name="fileTime" type="text" style="width:350px;height:30px" disabled/>&nbsp;&nbsp;&nbsp;&nbsp;
                               <input style="display:none;" id="fileSize" name="fileSize" type="text" style="width:350px;height:30px" disabled/>&nbsp;&nbsp;&nbsp;&nbsp;
                               <a style="display:none;" id="uploadBt"  class="button-gray" id="upload" class="button-gray">选择文件</a>
                               <div id="console" style="color:red;margin: -20px -366px;"></div>
                           </div>

调用上传代码

 if(!set_upload_param(uploader, '', false)){
            return false;
        }

猜你喜欢

转载自my.oschina.net/u/1052192/blog/1819795