1. 程式人生 > >前端上傳圖片到oss服務,模仿微博多張圖片上傳(最多九張)

前端上傳圖片到oss服務,模仿微博多張圖片上傳(最多九張)

效果圖如下
在這裡插入圖片描述

在這裡插入圖片描述

核心js檔案

  • 推薦《前端上傳元件Plupload使用指南》,有較詳細使用指南。
  • 檔案地址:
https://www.cnblogs.com/2050/p/3913184.html#plupload_doc4
首先是css檔案的引入
  • 上傳元件的css
  <link rel="stylesheet" href='../css/uploadOss.css'/>

-引入jq和upload 核心js檔案

<script src="../js/commonJs/jquery.min.js"></script>
<script type="text/javascript" src="../js/commonJs/plupload.full.min.js"></script>

-html結構(具體細節圖按照各位ui公司的圖進行頁面和樣式開發,在這隻介紹使用用法)

<a href="###" class="gc_tp"><em class="tellbox_tp"></em>圖片<input type="file" id="choose_pic_click_1" name="file" multiple="multiple"  onmousedown="mouseDown_check(this)" accept="image/*"></a>
//釋出傳參
var pic_list = [];
var pushStr = '';
var publicParams = {};
publicParams.u = $.cookie('uid');//uid
publicParams.text = '';         //訊息文字   注意替換一下游戲
publicParams.title = '說點什麼來記錄今天';    //訊息標題   說點什麼來記錄今天
publicParams.pic = '';          //訊息圖片
publicParams.video = '';        //訊息視訊
publicParams.video_cover = '';  //視訊封面
publicParams.video_title = '';	//視訊標題
publicParams.f_type = 1;        //訊息來源型別 int
publicParams.visible = 0;     //訊息可見性
//公用部分
var accessid = '';
var accesskey = '';
var host = '';
var policyBase64 = '';
var signature = '';
var callbackbody = '';
var filename = '';
var key = '';
var expire = 0;
var g_object_name = '';
var g_object_name_type = '';
var now = timestamp = Date.parse(new Date()) / 1000;

//增加引數
var video_face;//視訊封面的檔案儲存
function send_request_video() {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp != null) {
        serverUrl = '換成你自己的請求地址';//第一次請求地址
        xmlhttp.open("POST", serverUrl, false);
        xmlhttp.send(null);
        return xmlhttp.responseText
    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }
}
//圖片上傳
function send_request_pic() {

    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp != null) {
        serverUrl = '換成你自己的請求地址';//第一次請求地址
        xmlhttp.open("POST", serverUrl, false);
        xmlhttp.send(null);
        return xmlhttp.responseText
    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }
}

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length; i++) {
        if (tt[i].checked) {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_signature() {
    //可以判斷當前expire是否超過了當前時間,如果超過了當前時間,就重新取一下.3s 做為緩衝
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        body = send_request_video();
        body = JSON.parse(body);
        //console.log(body, body.Result);
        var obj = eval("(" + body.Result + ")");
        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 get_signature_pic() {
    //可以判斷當前expire是否超過了當前時間,如果超過了當前時間,就重新取一下.3s 做為緩衝
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        body = send_request_pic();
        body = JSON.parse(body);

        var obj = eval("(" + body.Result + ")");
        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, is_set_w_h, w, h) {
    if (g_object_name_type == 'local_name') {
        g_object_name += "${filename}";
    }
    else if (g_object_name_type == 'random_name') {
        suffix = get_suffix(filename);
        var re_key = key + random_string(32);
        if (is_set_w_h) {
            re_key += "|" + w + "|" + h;
        }
        g_object_name = re_key + suffix;
    }
    return ''
}

function get_uploaded_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        tmp_name = g_object_name;
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if (g_object_name_type == 'random_name') {
        return g_object_name
    }
}
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 set_upload_param_pic(up, filename, ret) {

    if (ret == false) {
        ret = get_signature_pic();
    }
    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 mouseDown_check(node) {
    if ($('#content').css('display') == 'block') {
        layer.open({
            title: '提示',
            content: '確定放棄上傳視訊嗎?',
            yes: function (index) {
                layer.close(index);
                close_();
            }
        });
    } else {
        $('#choose_pic_click_1').click();
    }
}

var uploader_pic = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: ["choose_pic_click_1", "choose_pic_click"],
    multi_selection: true,//上傳多個
    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: [ //只允許上傳圖片和zip檔案
            {title: "Image files", extensions: "jpg,gif,png,bmp"},
        ],
//            mime_types: [],
        max_file_size: '10mb', //最大隻能上傳10mb的檔案
        prevent_duplicates: true //不允許選取重複檔案
    },

    init: {
        PostInit: function () {
            document.getElementById('ossfile').innerHTML = '';
        },
        FilesAdded: function (up, files) {
            if ($('.tp_fatherBox').css('display') == 'none') {
                number_canUp();
                $('.tp_fatherBox').css('display', 'block');
                $("#choose_pic_click_1").attr('disabled', 'disabled');
            } else {
                $("#choose_pic_click_1").removeAttr('disabled');
            }


            if (files.length > $("#can_upNumber").html()) {
                layer.open({
                    title: '提示',
                    content: '超過了可新增數量!'
                });
                up.files = '';
                up.total.reset();
                return
            } else {
                var strs = '';
                plupload.each(files, function (file) {
                    strs += '<div class="contribute_choosePicLi"  id="' + file.id + '"><span class="picbg"></span><span class="contribute_delete" onclick=\'delete_pic("' + file.id + '")\'></span><img  class="choose_pic"><div class="progress"><div class="progress-bar" style="width: 0%"></div></div></div>';

                });
                $("#listPic").append(strs);
                set_upload_param_pic(up, '', false);
            }
        },

        BeforeUpload: function (up, file) {
            check_object_radio();
            set_upload_param_pic(up, file.name, true);
            //var w = 0, h = 0;
            //var MyTest = file.getNative();
            //var reader = new FileReader();
            //reader.readAsDataURL(MyTest);
            //reader.onload = function (theFile) {
            //    var image = new Image();
            //    image.src = theFile.target.result;
            //    image.onload = function () {
            //        w = this.width;
            //        h = this.height;
            //    };
            //};
            //
            //set_upload_param_pic(up, file.name, true, true, w, h);
        },

        UploadProgress: function (up, file) {
            var d = $("#listPic").find('div#' + file.id);
            var prog = d.find('div').eq(0);
            var progBar = d.find('div').eq(0);
            progBar.css('width', '100%');
            progBar.attr('aria-valuenow', file.percent);
            number_canUp();
        },

        FileUploaded: function (up, file, info) {
            number_canUp();
            if (info.status == 200) {
                var self_info = JSON.parse(info.response).Result;
                pic_list.push(self_info.name + '$' + self_info.width + '$' + self_info.height);
                $('#' + file.id).find('img').attr('src', self_info.name);
                $('#' + file.id).find('div.progress').css('display', 'none');
//                    document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name) + '回撥伺服器返回的內容是:' + info.response;
            }
            else if (info.status == 203) {
                layer.open({
                    title: '提示',
                    content: '上傳到OSS成功,但是oss訪問使用者設定的上傳回調伺服器失敗,失敗原因是:' + info.response,
                    yes: function (index) {
                        layer.close(index);
                    }
                });
            }
            else {
                layer.open({
                    title: '提示',
                    content: info.response,
                    yes: function (index) {
                        layer.close(index);

                    }
                });
            }
        },
        UploadComplete: function (up, file) {
        },
        Error: function (up, err) {
            if (err.code == -600) {
                layer.msg('選擇的檔案太大了,可以根據應用情況,在upload.js 設定一下上傳的最大大小', {time: 600});
            }
            else if (err.code == -601) {
                layer.msg('選擇的檔案字尾不對,可以根據應用情況,在upload.js進行設定可允許的上傳檔案型別', {time: 600});
            }
            else if (err.code == -602) {
                layer.msg('這個檔案已經上傳過一遍了', {time: 600});
            }
            else {
                layer.msg("Error xml:" + err.response, {time: 800});
            }
        }
    }
});

uploader_pic.init();

function aa() {
    alert();
    var MyTest = document.getElementById("choose_pic_click_1").files[0];

    var reader = new FileReader();
    reader.readAsDataURL(MyTest);
    reader.onload = function (theFile) {
        var image = new Image();
        image.src = theFile.target.result;
        image.onload = function () {
            alert("圖片的寬度為" + this.width + ",長度為" + this.height);
        };
    };
}

//計算還可以插入幾張圖片
function number_canUp() {
    var now_ = $("#listPic").find('div.contribute_choosePicLi').length;
    $('#can_upNumber').html(Number(9 - now_));
}
function delete_pic(id) {
    $('#' + id).remove();
    layer.open({
        title: '提示',
        content: '刪除成功'
    });
    var test2 = document.getElementById('choose_pic_click');
    test2.value = '';
    number_canUp();
}
function close_tpFtherbox() {
    $('#listPic').empty();
    publicParams.pic = '';
    pic_list = [];
    var test = document.getElementById('choose_pic_click_1');
    var test2 = document.getElementById('choose_pic_click');
    test.value = '';
    test2.value = '';
    $("#choose_pic_click_1").removeAttr('disabled');
    number_canUp();
    uploader_pic.files = '';
    uploader_pic.total.reset();
    $('.tp_fatherBox').css('display', 'none');
}