js预览图片+多图片+多选框的表单上传

1.js预览图片:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script type="text/javascript">
    function changepic() {
        //document.getElementById("#prompt3").css("display", "none");
        var reads = new FileReader();
        var f = document.getElementById('chosefile').files[0];
        reads.readAsDataURL(f);
        reads.onload = function(event) {
            document.getElementById('showimg').src = this.result;
            // document.getElementById("#img3").css("display", "block");
        };
    }
</script>
<body>
<div>
        <!--当vaule值改变时执行changepic函数,规定上传的文件只能是图片-->
        <input type="file" id="chosefile" style="width: 200px;height: 30px;" onchange="changepic()" accept="image/jpg,image/jpeg,image/png,image/PNG"><br>
        <img src="" id="showimg" style="width: 300px;height: 300px;" />
</div>
</body>
</html>

2.js+h5多图片上传:

参考文章:写的真的很棒====https://blog.csdn.net/huangxin112/article/details/74956462/

 
<!DOCTYPE html>    
<html>    
<head>    
<meta charset="UTF-8">    
<title>showImages</title>    
<style type="text/css">   
    .float{    
        float:left;    
        width : 200px;    
        height: 200px;    
        overflow: hidden;    
        border: 1px solid #CCCCCC;    
        border-radius: 10px;    
        padding: 5px;    
        margin: 5px;    
    }    
    img{    
        position: relative;    
    }    
    .result{    
        width: 200px;    
        height: 200px;    
        text-align: center;    
        box-sizing: border-box;    
    }   
  
  
    #file_input{  
        display: none;  
    }  
  
  
    .delete{  
        width: 200px;  
        height:200px;  
        position: absolute;  
        text-align: center;  
        line-height: 200px;  
        z-index: 10;  
        font-size: 30px;  
        background-color: rgba(255,255,255,0.8);  
        color: #777;  
        opacity: 0;  
        transition-duration: 0.7s;  
        -webkit-transition-duration: 0.7s;   
    }  
  
  
    .delete:hover{  
        cursor: pointer;  
        opacity: 1;  
    }  
  
  
        
</style>    
    
    
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>    
<script type="text/javascript">    
    
    
window.onload = function(){    
    var input = document.getElementById("file_input");    
    var result;    
    var dataArr = []; // 储存所选图片的结果(文件名和base64数据)  
    var fd;  //FormData方式发送请求    
    var oSelect = document.getElementById("select");  
    var oAdd = document.getElementById("add");  
    var oSubmit = document.getElementById("submit");  
    var oInput = document.getElementById("file_input");  
     
    if(typeof FileReader==='undefined'){    
        alert("抱歉,你的浏览器不支持 FileReader");    
        input.setAttribute('disabled','disabled');    
    }else{    
        input.addEventListener('change',readFile,false);    
    }     //handler    
    
        
    function readFile(){   
        fd = new FormData();    
        var iLen = this.files.length;  
        for(var i=0;i<iLen;i++){  
            if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){  //判断上传文件格式    
                return alert("上传的图片格式不正确,请重新选择");    
            }  
            var reader = new FileReader();  
            fd.append(i,this.files[i]);  
            reader.readAsDataURL(this.files[i]);  //转成base64    
            reader.fileName = this.files[i].name;  
  
            reader.onload = function(e){   
                var imgMsg = {    
                    name : this.fileName,//获取文件名    
                    base64 : this.result   //reader.readAsDataURL方法执行完后,base64数据储存在reader.result里    
				}   
                dataArr.push(imgMsg);    
                result = '<div class="delete">delete</div><div class="result"><img class="subPic" src="'+this.result+'" alt="'+this.fileName+'"/></div>';    
                var div = document.createElement('div');  
                div.innerHTML = result;    
                div['className'] = 'float';  
                document.getElementsByTagName('body')[0].appendChild(div);    //插入dom树    
                var img = div.getElementsByTagName('img')[0];  
                img.onload = function(){    
                    var nowHeight = ReSizePic(this); //设置图片大小    
                    this.parentNode.style.display = 'block';    
                    var oParent = this.parentNode;    
                    if(nowHeight){    
                        oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';    
                    }    
                }   
                div.onclick = function(){  
                    $(this).remove();                  // 在页面中删除该图片元素  
                }  
            }    
        }    
    }    
        
        
    function send(){   
        var submitArr = [];  
        $('.subPic').each(function () {
                submitArr.push({
                    name: $(this).attr('alt'),
                    base64: $(this).attr('src')
                });  
            }
        );
        $.ajax({    
            url : 'http://123.206.89.242:9999',    
            type : 'post', 
            data : JSON.stringify(submitArr),    
            dataType: 'json',    
            //processData: false,   用FormData传fd时需有这两项    
            //contentType: false,    
            success : function(data){    
                console.log('返回的数据:'+JSON.stringify(data))    
           }
        })    
    }    
        
     
  
  
    oSelect.onclick=function(){   
        oInput.value = "";   // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发  
        //清空已选图片  
        $('.float').remove();        
        oInput.click();   
    }   
  
  
    oAdd.onclick=function(){  
        oInput.value = "";   // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发  
        oInput.click();   
    }   
  
  
    oSubmit.onclick=function(){    
        if(!dataArr.length){    
            return alert('请先选择文件');    
		}    
        send();    
    }    
}    
/*    
 用ajax发送fd参数时要告诉jQuery不要去处理发送的数据,    
 不要去设置Content-Type请求头才可以发送成功,否则会报“Illegal invocation”的错误,    
 也就是非法调用,所以要加上“processData: false,contentType: false,”    
 * */    
    
                
function ReSizePic(ThisPic) {    
    var RePicWidth = 200; //这里修改为您想显示的宽度值    
    
    var TrueWidth = ThisPic.width; //图片实际宽度    
    var TrueHeight = ThisPic.height; //图片实际高度    
        
    if(TrueWidth>TrueHeight){    
        //宽大于高    
        var reWidth = RePicWidth;    
        ThisPic.width = reWidth;    
        //垂直居中    
        var nowHeight = TrueHeight * (reWidth/TrueWidth);    
        return nowHeight;  //将图片修改后的高度返回,供垂直居中用    
    }else{    
        //宽小于高    
        var reHeight = RePicWidth;    
        ThisPic.height = reHeight;    
    }    
}    
 
    
                
</script>    
</head>    
    <body>    
            <div class="container">    
                <label>请选择一个图像文件:</label>  
                <button id="select">(重新)选择图片</button>  
                <button id="add">(追加)图片</button>  
                <input type="file" id="file_input" multiple/> <!--用input标签并选择type=file,记得带上multiple,不然就只能单选图片了-->    
                <button id="submit">提交</button>
            </div>    
    </body>    
</html> 

补充:

上传图片提交ajax
如果想把图片信息通过ajax传给后端,则需要通过new FormData() 上传图片信息,然后使用 append() 方法向该对象里添加字段,具体代码如下:

(注:以下代码在图片预览成功后执行,也就是在reader.readAsDataURL(file); 后)
 

var formData = new FormData(); 
formData.append('file', $('#input_file')[0].files[0]);  //添加图片信息的参数  //var c=document.getElementById('limg').files[0]       这里c是二进制blob变量   $('#input_file')[0]是取查到的id为input_file的第一个元素
formData.append('sizeid',123);  //添加其他参数
$.ajax({
    url: '/material/uploadFile',
    type: 'POST',
    cache: false, //上传文件不需要缓存
    data: formData,
    processData: false, // 告诉jQuery不要去处理发送的数据
    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
    success: function (data) {
        var rs = eval("("+data+")");
        if(rs.state==1){
            tipTopShow('上传成功!');
        }else{
            tipTopShow(rs.msg);
        }
    },
    error: function (data) {
        tipTopShow("上传失败");
    }
})  

3.servlet获取h5传来的复选框数据:

String [] likes=request.getParameterValues("like");

一般的使用String username=request.getParameter("username");就可以了

猜你喜欢

转载自blog.csdn.net/qq_41063141/article/details/88841642