基于jQuery实现的图片上传

首先需要引入一个jQuery文件,然后更改附件服务器的地址及上传时要的相关参数,以下代码使用的是FormData方式上传可以兼容到ie10及以上。支持多选图片上传。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>附件上传</title>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>		
<style type="text/css">
	*{
		box-sizing: content-box;
		margin: 0;
	}
    .imageDiv {
        display:inline-block;
        width:120px;
        height:120px;
        -webkit-box-sizing:border-box;
        -moz-box-sizing:border-box;
        box-sizing:border-box;
        border:1px dashed darkgray;
        background:#f8f8f8;
        position:relative;
        overflow:hidden;
        margin:10px 5px;
    }
    .cover {
        position:absolute;
        z-index:1;
        top:0;
        left:0;
        width:120px;
        height:120px;
        background-color:rgba(0,0,0,.3);
        display:none;
        line-height:125px;
        text-align:center;
        cursor:pointer;
    }
    .cover .delbtn {
        color:red;
        font-size:20px;
    }
    .imageDiv:hover .cover {
        display:block;
    }
    .addImages {
        display:inline-block;
        width:120px;
        height:120px;
        -webkit-box-sizing:border-box;
        -moz-box-sizing:border-box;
        box-sizing:border-box;
        border:1px dashed darkgray;
        background:#f8f8f8;
        position:relative;
        overflow:hidden;
        margin:10px 5px;
    }
    .text-detail {
    	width: 100%;
    	height: 100%;
        text-align: center;
    }
    .text-detail span {
    	line-height: 118px;
        font-size:80px;
        cursor:pointer;
        width: 100%;
        height: 100%;
        display: inline-block;
    }
    .file{
       display:none;
    }
    #img{
		overflow:hidden;
		width:100%;
		min-height: 106px;
    }
	.deleteimg{
		position:absolute;
		top:0;
		right:0;
		color:#fff;
		background:#f00;
		width:20px;
		height:20px;
		text-align:center;
		cursor:pointer;
		border-radius: 50%;
		font-weight: bold;
	}
	button{
		background-color:#5aa9d4;
		border: none;
		color:#fff;
		height: 35px;
		width: 50px;
		cursor: pointer;
		margin-left: 5px;
	}
</style>
</head>
<body>
	<!-- 图片上传模块 -->
	<div id="Pic_pass" style="overflow:hidden;">
		<p style="font-size: 15px;font-weight: bold;text-indent:1em;">请上传图片</p>
		<div id="img"></div>
		<div class="picDiv">
		    <div class="addImages">
		        <input type="file" class="file" id="uploadFilexxx" multiple="multiple" accept="image/png, image/jpeg, image/gif, image/jpg">
		        <div class="text-detail">
		            <span onclick="choseimg(this)">+</span>
		        </div>
		    </div>
		    <div>
		    	<button type="button" id="bbt">上传</button>
		    </div>
		</div>
	</div>
	<!-- 图片预览模块 -->
	<div id='fjView' style="width:100%;height: 100%;position: absolute;top:0;background:rgba(0,0,0,0.5);display: none;">
		<div style="max-width:60%;height: 515x;background: #fff;margin: 10px auto;text-align: center;position: relative;overflow:hidden;">
			<img id='imgView' src='' height="480px"/>
			<span style="position: absolute;top:0;right: 0;width: 30px;height: 30px;color:#f00;line-height: 30px;font-size: 30px;cursor: pointer;" onclick="$('#fjView').css('display','none')">x</span>
			<div style="height: 35px;">
				<button onclick="$('#fjView').css('display','none')">关闭</button>
				<button onclick="viewP()">上一张</button>
				<button onclick="viewN()">下一张</button>
			</div>
		</div>
	</div>
<script type="text/javascript">
	var baseUrl='http://10.41.253.146:8066/fjgl';		//附件服务器地址
	var fjViewUrl='http://10.41.253.146:8012/onlinePreview?url=';	//附件预览地址
	var fjDownUrl='http://10.41.253.146:8066/fjgl/file/option?open=0&url=';	//附件下载地址
	var ztid='23c775';		//测试用的主体id
	var fwid='fwid';								//服务id
	var fwmy='fwmy';		//服务密钥
	var fileViewList=new Array();		//存放将要预览的图片url数组
	var FILES=new Array();				//存放input所有选择好的file对象集合

	$(function() {
		 getfile();
	});

	function Random(n) {
        var randomArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        var value = '';
        for (var i = 0; i < n; i++) {
            value += randomArray[Math.floor(Math.random() * randomArray.length)];
        }
        return value;
    }

	function getfile(){
		fileViewList=[];
		$("#img").html('');
		$.ajax({
	        url:baseUrl+'/file/get',
	        dataType:'json',
	        type:'post',
	        data:{'modelId':ztid,'fwid':fwid,'fwmy':fwmy},	         
	        success:function(data){
	            if(data.code==1&&data.obj!=null&&data.obj.length>0){
			          $.each(data.obj,function(index,value){
			            var viewURL=fjViewUrl+encodeURIComponent(fjDownUrl+value.fjurl+'&fileName='+Random(16)+'&fullfilename='+Random(16)+value.fjmc);
			            var src=baseUrl+"/file/option?url="+value.fjurl;	//图片地址
			            fileViewList.unshift(src);
			            var picHtml = "<div style='position:relative;display:inline-block;margin:0 5px;border:1px solid #eee;'><img style='height:100px;cursor:pointer;' οnclick='imgClick(this)' src="+src+ "><div class='deleteimg' οnclick='delImg(\""+value.fjid+"\")'>-</div></div";
			          	$('#img').prepend(picHtml);       	  		   
			          })
	            }
	        }
	    })
	}

	function imgClick(source){
		var fjView = document.getElementById("fjView");
		fjView.style.display='block';
		$("#imgView").attr('src',source.src);
	}

	function viewP(){	//查看上一张图片
		var currenturl=$("#imgView").attr('src');
		var currentIndex=fileViewList.indexOf(currenturl);
		if(currentIndex==0){
			currentIndex=fileViewList.length-1;
		}else{
			currentIndex--;
		}
		$("#imgView").attr('src',fileViewList[currentIndex]);
	}

	function viewN(){	//查看下一张图片
		var currenturl=$("#imgView").attr('src');
		var currentIndex=fileViewList.indexOf(currenturl);
		if(currentIndex==fileViewList.length-1){
			currentIndex=0;
		}else{
			currentIndex++;
		}
		$("#imgView").attr('src',fileViewList[currentIndex]);
	}

	function delImg(fjid){
		$.ajax({
	        url:baseUrl+'/file/delete',
	        dataType:'json',
	        type:'post',
	        data:{'ids':fjid,'fwid':fwid,'fwmy':fwmy},	         
	        success:function(data){
	            if(data.code==1){
	            	$("#img").html('');
	            	getfile(ztid);
	            }
	        }
	    })
	}

	function choseimg(obj) {
	    $this=$(obj);
	    $this.parents('div').prev('input').click();
	}

	$(".file").change(function() {
	    var docObj = $(this)[0];
	    var picDiv = $(this).parents(".picDiv");
	    var fileList = docObj.files;
	    for(var i=0; i<fileList.length;i++){
	    	FILES.push(fileList[i]);
	    }    
	    for (var i = 0; i < fileList.length; i++) {
	        var picHtml = "<div class='imageDiv' nm='"+fileList[i].name+"'><img id='img" + fileList[i].name + "' /> <div class='cover'><i class='delbtn'>删除</i></div></div>";
	        picDiv.prepend(picHtml);
	        var imgObjPreview = document.getElementById("img" + fileList[i].name);
	        if (fileList && fileList[i]) {	        	
	            imgObjPreview.style.display = 'block';
	            imgObjPreview.style.width = '120px';
	            imgObjPreview.style.height = '120px';
				imgObjPreview.src=window.URL.createObjectURL(fileList[i]);
	        }
	    }

	    $(".delbtn").click(function() {
	    	var _this = $(this);
	    	var nm=_this.parents(".imageDiv").attr("nm");	//用来存放当前要删除的文件名称
	    	for(var i=0;i<FILES.length;i++){
	    		if(FILES[i].name==nm){
	    			FILES.splice(i,1);
	    			break;
	    		}
	    	}
            _this.parents(".imageDiv").remove();
        });
	});

	$("#bbt").click(function(){
		var formData = new FormData();
		formData.append("fwmy",fwmy);
		formData.append("fwid",fwid);
		formData.append("ztid",ztid);
		if(FILES.length==0){		//没有上传图片
			return;
		}else{
			for(var i=0;i<FILES.length;i++){
				formData.append("files",FILES[i]);
			}
			$.ajax({
	        url:baseUrl+'/file/upload',
	        dataType:'json',
	        type:'post',
	        async: false,
	        data:formData,
	        processData:false,
	        contentType: false,
	        success:function(data){
	            if(data.code==1){
	            	$(".imageDiv").remove();
	            	FILES=[];	
	            	getfile();
	            }else{
	            	console.log('上传失败!')
	            }
	        }
	    })
		}
	})
</script>
</body>
</html>

以下使用的submit方式上传

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>附件上传</title>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>		
<script type="text/javascript" src="jquery.form.js"></script>
<style type="text/css">
	*{
		box-sizing: content-box;
		margin: 0;
	}
    .imageDiv {
        display:inline-block;
        width:120px;
        height:120px;
        -webkit-box-sizing:border-box;
        -moz-box-sizing:border-box;
        box-sizing:border-box;
        border:1px dashed darkgray;
        background:#f8f8f8;
        position:relative;
        overflow:hidden;
        margin:10px 5px;
    }
    .cover {
        position:absolute;
        z-index:1;
        top:0;
        left:0;
        width:120px;
        height:120px;
        background-color:rgba(0,0,0,.3);
        display:none;
        line-height:125px;
        text-align:center;
        cursor:pointer;
    }
    .cover .delbtn {
        color:red;
        font-size:20px;
    }
    .imageDiv:hover .cover {
        display:block;
    }
    .addImages {
        display:inline-block;
        width:120px;
        height:120px;
        -webkit-box-sizing:border-box;
        -moz-box-sizing:border-box;
        box-sizing:border-box;
        border:1px dashed darkgray;
        background:#f8f8f8;
        position:relative;
        overflow:hidden;
        margin:10px 5px;
    }
    .text-detail {
    	width: 100%;
    	height: 100%;
        text-align: center;
    }
    .text-detail span {
    	line-height: 118px;
        font-size:80px;
        cursor:pointer;
        width: 100%;
        height: 100%;
        display: inline-block;
    }
    .file{
       display:none;
    }
    #img{
		overflow:hidden;
		width:100%;
		min-height: 106px;
    }
	.deleteimg{
		position:absolute;
		top:0;
		right:0;
		color:#fff;
		background:#f00;
		width:20px;
		height:20px;
		text-align:center;
		cursor:pointer;
		border-radius: 50%;
		font-weight: bold;
	}
	button{
		background-color:#5aa9d4;
		border: none;
		color:#fff;
		height: 35px;
		width: 50px;
		cursor: pointer;
		margin-left: 5px;
	}
</style>
</head>
<body>
	<!-- 图片上传模块 -->
	<div id="Pic_pass" style="overflow:hidden;">
		<p style="font-size: 15px;font-weight: bold;text-indent:1em;">请上传图片</p>
		<div id="img"></div>
		<div class="picDiv">
		    <div class="addImages">
			<form  method="post" id="submitForm">
		        <input type="file" class="file" id="upload" multiple="multiple" accept="image/png, image/jpeg, image/gif, image/jpg">
                <div class="text-detail">
		            <span onclick="choseimg(this)">+</span>
		        </div>
                <input type="hidden" name="fwid" value="htxxxxgl" />
                <input type="hidden" name="fwmy" value="3182cf5d2b80f1dabb5d1003d6acb762"/>
                <input type="hidden" name="ztid" value="23c77563dd66417c8487740b32e7f3d3" />
                <input style="display: none" id ='sub' type="submit" value="Submit" />
            </form>
		    </div>
		    <div>
		    	<button type="button" id="bbt">上传</button>
		    </div>
		</div>
	</div>
	<!-- 图片预览模块 -->
	<div id='fjView' style="width:100%;height: 100%;position: absolute;top:0;background:rgba(0,0,0,0.5);display: none;">
		<div style="max-width:60%;height: 515px;background: #fff;margin: 10px auto;text-align: center;position: relative;overflow:hidden;">
			<img id='imgView' src='' height="480px"/>
			<span style="position: absolute;top:0;right: 0;width: 30px;height: 30px;color:#f00;line-height: 30px;font-size: 30px;cursor: pointer;" onclick="$('#fjView').css('display','none')">x</span>
			<div style="height: 35px;">
				<button onclick="$('#fjView').css('display','none')">关闭</button>
				<button onclick="viewP()">上一张</button>
				<button onclick="viewN()">下一张</button>
			</div>
		</div>
	</div>
<script type="text/javascript">
	var baseUrl='http://117.41.253.146:8066/fjgl';		//附件服务器地址
	var fjViewUrl='http://117.41.253.146:8012/onlinePreview?url=';	//附件预览地址
	var fjDownUrl='http://117.41.253.146:8066/fjgl/file/option?open=0&url=';	//附件下载地址
	var ztid='23c77563dd66417c8487740b32e7f3d3';		//测试用的旅馆主体id
	var fwid='htxxxxgl';								//服务id
	var fwmy='3182cf5d2b80f1dabb5d1003d6acb762';		//服务密钥
	var fileViewList=new Array();		//存放将要预览的图片url数组
	var FILES=new Array();				//存放input所有选择好的file对象集合

	$(function() {
        getfile();
        let options = {
            type: 'POST',
            url: baseUrl+'/file/upload',
            dataType:'json',
            resetForm: true ,// 是否重置form
            success:function(data){
                if(data.code == 1){
                    $(".imageDiv").remove();
                    FILES=[];
                    getfile();
                }else{
                    console.log('上传失败!')
                }
            }
        };
        $("#submitForm").submit(function(){
            if ( FILES.length!== 0){
                $(this).ajaxSubmit(options);
            }
            return false;  //防止表单自动提交
        });
	});

	function Random(n) {
        var randomArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        var value = '';
        for (var i = 0; i < n; i++) {
            value += randomArray[Math.floor(Math.random() * randomArray.length)];
        }
        return value;
    }

	function getfile(){
		fileViewList=[];
		$("#img").html('');
		$.ajax({
	        url:baseUrl+'/file/get',
	        dataType:'json',
	        type:'post',
	        data:{'modelId':ztid,'fwid':fwid,'fwmy':fwmy},	         
	        success:function(data){
	            if(data.code==1&&data.obj!=null&&data.obj.length>0){
			          $.each(data.obj,function(index,value){
			            var viewURL=fjViewUrl+encodeURIComponent(fjDownUrl+value.fjurl+'&fileName='+Random(16)+'&fullfilename='+Random(16)+value.fjmc);
			            var src=baseUrl+"/file/option?url="+value.fjurl;	//图片地址
			            fileViewList.unshift(src);
			            var picHtml = "<div style='position:relative;display:inline-block;margin:0 5px;border:1px solid #eee;'><img style='height:100px;cursor:pointer;' οnclick='imgClick(this)' src="+src+ "><div class='deleteimg' οnclick='delImg(\""+value.fjid+"\")'>-</div></div";
			          	$('#img').prepend(picHtml);       	  		   
			          })
	            }
	        }
	    })
	}

	function imgClick(source){
		var fjView = document.getElementById("fjView");
		fjView.style.display='block';
		$("#imgView").attr('src',source.src);
	}

	function viewP(){	//查看上一张图片
		var currenturl=$("#imgView").attr('src');
		var currentIndex=fileViewList.indexOf(currenturl);
		if(currentIndex==0){
			currentIndex=fileViewList.length-1;
		}else{
			currentIndex--;
		}
		$("#imgView").attr('src',fileViewList[currentIndex]);
	}

	function viewN(){	//查看下一张图片
		var currenturl=$("#imgView").attr('src');
		var currentIndex=fileViewList.indexOf(currenturl);
		if(currentIndex==fileViewList.length-1){
			currentIndex=0;
		}else{
			currentIndex++;
		}
		$("#imgView").attr('src',fileViewList[currentIndex]);
	}

	function delImg(fjid){
		$.ajax({
	        url:baseUrl+'/file/delete',
	        dataType:'json',
	        type:'post',
	        data:{'ids':fjid,'fwid':fwid,'fwmy':fwmy},	         
	        success:function(data){
	            if(data.code==1){
	            	$("#img").html('');
	            	getfile(ztid);
	            }
	        }
	    })
	}

	function choseimg(obj) {
	    $this=$(obj);
	    $this.parents('div').prev('input').click();
	}

	$(".file").change(function() {
	    var docObj = $(this)[0];
	    var picDiv = $(this).parents(".picDiv");
	    var fileList = docObj.files;
	    for(var i=0; i<fileList.length;i++){
	    	FILES.push(fileList[i]);
	    }    
	    for (var i = 0; i < fileList.length; i++) {
	        var picHtml = "<div class='imageDiv' nm='"+fileList[i].name+"'><img id='img" + fileList[i].name + "' /> <div class='cover'><i class='delbtn'>删除</i></div></div>";
	        picDiv.prepend(picHtml);
	        var imgObjPreview = document.getElementById("img" + fileList[i].name);
	        if (fileList && fileList[i]) {	        	
	            imgObjPreview.style.display = 'block';
	            imgObjPreview.style.width = '120px';
	            imgObjPreview.style.height = '120px';
				imgObjPreview.src=window.URL.createObjectURL(fileList[i]);
	        }
	    }

	    $(".delbtn").click(function() {
	    	var _this = $(this);
	    	var nm=_this.parents(".imageDiv").attr("nm");	//用来存放当前要删除的文件名称
	    	for(var i=0;i<FILES.length;i++){
	    		if(FILES[i].name==nm){
	    			FILES.splice(i,1);
	    			break;
	    		}
	    	}
            _this.parents(".imageDiv").remove();
        });
	});

	$("#bbt").click(function(){
        $('#sub').click();
	})
 
</script>
</body>
</html>

效果如下图所示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值