前端上传图片到oss服务,模仿微博多张图片上传(最多九张)

效果图如下
前端上传图片到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');
}