多张图片上传预览及上传到服务器

这周搞混合开发的时候给app提供帮助反馈页面,里面有图片上传功能。之前做过图片上传预览,但是上传到服务器用的插件,对于把图片上传到服务器的方法并不清楚。查了一些资料大部分也都是关于图片预览的,还好有上传到服务器的例子,根据例子做了一些修改方便用在移动端(注:在混合开发app中应用可能会有app屏蔽点击input type=file的方法),当然PC端也是可以用的。可以获取到图片的名称、大小和类型。没有写成插件方便在不同的情况下使用,效果当然没有插件好用,但是贵在学习了一种方法,下面就直接把全部代码贴出来:


转载请注明出处
更新-----2018.9.28 更新兼容iOS

全部代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport" />
    <title>上传图片</title>
    <style>
        input[type="file"] {
            display: none;
        }
        img {
            width: 30%;
            margin: 10px 0 10px 2.2%;
            border: 1px solid #ccc;
            vertical-align: top;
        }
        #imgDiv {
            background-color: #EEEEEE;
            text-align: left;
            min-height: 111px;
        }
        #uploadDiv {
            text-align: right;
        }
        .file {
            border: 1px solid #39C468;
            color: #39C468;
            height: 35px;
            padding: 0 10px;
            width: 80px;
            border-radius: 5px;
            background-color: white;
            font-size: 90%;
            margin-top: 10px;
        }
        #editerBtn {
            width: 80%;
            background-color: #39C468;
            color: white;
            height: 40px;
            display: block;
            margin: auto;
            margin-top: 40px;
            margin-bottom: 40px;
            border: none;
            border-radius: 5px;
        }

    </style>
</head>
<body>
<main>
    <div id="sendQuestion">
        <form id="addFeedbackForm">
            <div id="photos">
                <!--我这里限制的是5张图,所以加了5file-->
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <input type="file" data-file="" class="noImgUrl" onchange="showPic(this)">
                <div id="imgDiv">
                </div>
                <div id="uploadDiv">
                    <input type="button" class="file" value="添加图片"/>
                </div>
            </div>
            <input type="button" value="提交" id="editerBtn">
        </form>
    </div>
</main>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script>
    $(".file").click(function(){
        var imgLength = document.getElementById('imgDiv').children.length;
        /*判断图片大于5*/
        if(imgLength >= 5){
            alert('最多上传5张图');
            return false;
        }
        /*每次点击相当于添加图片相当于点击了.noImgUrl的第一个file*/
        document.getElementsByClassName('noImgUrl')[0].click();
    });
    //提交反馈
    $("#editerBtn").click(function () {
        uploadFile();
    });
    // 上传图片
    function uploadFile() {
        var xhr = new XMLHttpRequest();
        /*FormData,我们就可以轻松地使用Ajax方式进行文件上传了,参数自动获取form里name的值*/
        var fd = new FormData(document.getElementById('addFeedbackForm'));

        /* 事件监听 */
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
         xhr.addEventListener("error", uploadFailed, false);
         xhr.addEventListener("abort", uploadCanceled, false);
        /* 上传服务器端的URL ,参数自动获取form里name的值*/
        xhr.open("POST", "../appFeedBackHelp/feedBack.do");
        xhr.send(fd);
    }

    function uploadProgress(evt) {

    }

    function uploadComplete(evt) {
        /* 当服务器发送响应时,会引发此事件 */
        $("#editerBtn").removeAttr('disabled');
        console.info(JSON.parse(evt.target.responseText).httpCode);
        if(JSON.parse(evt.target.responseText).httpCode == 200){
            alert('上传成功');
        }else {
            alert('上传失败');
        }
    }

     function uploadFailed(evt) {
         alert('上传文件时出错');
     }

     function uploadCanceled(evt) {
         alert('上传被取消');
     }
    function showPic(obj) {
        var fullPath = getFullPath(obj);
        if (fullPath) {
            document.getElementById("pic").src = fullPath + "";
        }
    };
    //选择图片
    function getFullPath(obj) {
        //一次选择一张
        if (obj) {
            //Internet Explorer
            if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
                obj.select();
                return document.selection.createRange().text;
            }

            //兼容chrome、火狐等,HTML5获取路径
            if (typeof FileReader != "undefined") {
                var reader = new FileReader();
                try {
                    reader.onload = function (e) {
                        var fileData = obj.files[0];
                        /*这里读到的是图片大小,也可以在这里加入图片大小限制*/
                        var size = (fileData.size/1024).toFixed(1);
                        var type = fileData.type;
                        /*图片类型限制*/
                        if (type == 'image/png' ||type == 'image/jpeg' ||type == 'image/bmp' ||type == 'image/gif'){

                            console.info('图片大小:'+size+'KB','类型:'+type);
                            document.getElementById('imgDiv').innerHTML += '<img name="'+obj.files[0].name+'" type="image" class="uploadImg" onclick="deleteImg(this)" src="' + e.target.result + '"/>';
                            $(".uploadImg").height($(".uploadImg").width());
                            $(obj).attr({'name':'imageFileName','data-file':obj.files[0].name});
                            $(obj).removeClass('noImgUrl');

                        }else {
                            alert('只允许上传jpg、png、gif、bmp格式的图片');
                            return false;
                        }
                    };
                    reader.readAsDataURL(obj.files[0]);
                } catch (err) {
                    console.info(err.message);
                }
            } else if (browserVersion.indexOf("SAFARI") > -1) {
                alert("暂时不支持Safari浏览器!");
            }else {
                alert("浏览器暂时不支持!");
            }

        }
    };
    //删除图片
    function deleteImg(obj) {
        var check = confirm('是否确定删除');
        if (check){
            //查找删除img对应的input
            for (var x = 0;x < $("input[type='file']").length;x++){
                if($("input[type='file']").eq(x).attr('data-file') == $(obj).attr('name')){
                    console.info($("input[type='file']").eq(x).attr('data-file'),$(obj).attr('name'),x);
                    $("input[type='file']").eq(x).addClass('noImgUrl');
                    $("input[type='file']").eq(x).removeAttr('name');
                    $("input[type='file']").eq(x).removeAttr('data-file');
                    $(obj).remove();
                    return false;
                }
            }
        }
    }
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值