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

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


转载请注明出处

全部代码

<!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张图,所以加了5个file-->
                <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;
            }
            //Firefox
            if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
                if (obj.files) {
                    return obj.files.item(0).getAsDataURL();
                }
                return obj.value;
            }

            //兼容chrome、火狐等,HTML5获取路径
            if (typeof FileReader != "undefined") {
                var reader = new FileReader();
                if (obj.files.length > 1) {
                    layer.open({
                        content: '一次选择1张图'
                        , btn: '确定'
                    });
                    return false;
                } else {
                    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>

猜你喜欢

转载自blog.csdn.net/github_37125043/article/details/72723037