Ajax+servlet实现图片上传与预览、重选、删除

前端代码


<form  id="form1">

<input type="file" id="f1" name="f" onchange="setpicpath('form1','f1','show1')" />
<div id="show1"></div>
<button  id="reload" type="button" onclick="repic('f1','show1')">重新上传</button>
</form>
<div width="100%" height="10px"></div>
<form  id="form2">
<div id="show2"></div>
<input type="file" id="f2" name="f2" onchange="setpicpath('form2','f2','show2')"/>
<button  id="reload" type="button" onclick="repic('f2','show2')">重新上传</button>
</form>

这个现实两张图片的上传。每选择一张图片完成后,即可预览。这个时候要区分不同的表单。其实也可以在输入框定义id值即可达到标识的效果。这里为了美观,所以选择两张表单。

 function repic(inputid,show){
 //实现重现选择功能
	 var data= $("#"+inputid).val();
	 console.log(data);
	 $("#"+show).empty();
	 $.ajax({
		  url: "/mybatis_first_demo2/deletePicServlet", 
          type: 'GET',  
          data: "picpath="+data,  
          processData: false,
          contentType: false,
          dataType: 'json',  
          success:function(json){
        	  console.log("success delete");
        	  $("#"+inputid+"picpath").val(json[0]);
          },
	 error:function(){
        	  console.log("error");
          }
          
  
	 })
	  $("#"+inputid).click();
	
	 
 };
 function setpicpath(formid,inputid,show){
 //第一次选择图片
			 console.log("1223");
		     var animateimg = $("#"+inputid).val(); //获取上传的图片名 带//
		     var imgarr=animateimg.split('\\'); //分割
		     var myimg=imgarr[imgarr.length-1]; //去掉 // 获取图片名
		     var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
		     var ext = myimg.substring(houzui, myimg.length).toUpperCase();  //切割 . 获取文件后缀
		     
		     var file = $('#'+inputid).get(0).files[0]; //获取上传的文件
		     var fileSize = file.size;           //获取上传的文件大小
		     var maxSize = 10485760;              //最大10MB
		     if(ext !='.PNG' && ext !='.GIF' && ext !='.JPG' && ext !='.JPEG' && ext !='.BMP'){
		         alert('文件类型错误,请上传图片类型');
		     }else if(parseInt(fileSize) >= parseInt(maxSize)){
		        alert('上传的文件不能超过10MB');
		        
		         
		     }else{  
		    	 var username="一旬";
		         var data = new FormData($('#'+formid)[0]); 
		         console.log(data);
		         $.ajax({  
		             url: "/mybatis_first_demo2/insertPicPathServlet", 
		             type: 'POST',  
		             data: data,  
		             processData: false,
		             contentType: false,
		             dataType: 'json',  
		             success:function(json){
		            	 for(var i=0;i<json.length;i++){
		            		 console.log(json[i]);
		            		 //这个json字段是后台servlet返回的
		            		 当上传成功之后,servlet会返回图片的相对路径
		            			 $("#"+show).append("<img src=./images/"+username+"/"+json[i]+" width=200px height=200px;/>");
		            		 }
		            		
		            	 $("#"+inputid+"picpath").val(json[0]);
		            	 //这个代码是设置隐藏输入框的值,为了提交表单的时候,把图片的名称带过去,存入数据库。
		            	 console.log("inputidpicpath value"+json[0]);
		            	 $("#"+inputid).hide();
		            	 
		             },
		             error: function(json){
		            	 console.log("11111111");
		            	 alert("不能重复上传图片,请重新上传");
		             }
		             
		         })
		         
		        }  
		 
}
 

下面代码为servlet后台实现图片的上传到tomcat和向前端返回图片路径代码。以json形式返回

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		SqlSession session=null;
//		String text=request.getParameter("text");
//		String title=request.getParameter("title");
//		String username=request.getParameter("username");
//		Integer userID=Integer.parseInt(request.getParameter("userID"));
//		Integer date=Integer.parseInt((String)request.getAttribute("date"));
//		Integer userID=Integer.parseInt((String)request.getAttribute("userID"));
		String picpath1=null;
		String picpath2=null;
		String username="一旬";
		//为解析类提供配置信息 
		List<String>picpath=new ArrayList<String>();
		int num=0;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//创建解析类的实例 
		ServletFileUpload sfu = new ServletFileUpload(factory); 
		//开始解析 
		sfu.setFileSizeMax(10485760); 
		//10M
		//每个表单域中数据会封装到一个对应的FileItem对象上 
		try { 
		List<FileItem> items = sfu.parseRequest(request); 
		//区分表单域 
		for (int i = 0; i <items.size(); i++) { 
		FileItem item = items.get(i); 
		//isFormField为true,表示这不是文件上传表单域 
		if(!item.isFormField()){ 
		ServletContext sctx = getServletContext(); 
		if(sctx!=null) {
			//获得存放文件的物理路径 
			//upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹 
			String path = sctx.getRealPath("/images"); 
			System.out.println(path); 
			//获得文件名 
			String fileName = item.getName(); 
			System.out.println(fileName); 
			//该方法在某些平台(操作系统),会返回路径+文件名 
			fileName = fileName.substring(fileName.lastIndexOf("\\")+1); 
			File file = new File(path+"\\"+username+"\\"+fileName); 
			item.write(file); 
			//将上传图片的名字记录到数据库中 
			System.out.println("okwrite");
			System.out.println(file.getPath());
			request.setAttribute("picpath"+(i+1),fileName);
			System.out.println("picpath"+(i+1));
			picpath.add(fileName);
			num=i+1;
//			DataConnection conn=new DataConnection();
//			SqlSession sessionConnection=conn.getSession();
//			StudentMapper mapper=sessionConnection.getMapper(StudentMapper.class);
//			mapper.addPic(userID, picpath1, picpath2)

			
			
			
		}
		
		
		} 
		} 
		
		String jsonString = JSON.toJSONString(picpath);  
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("application/json; charset=utf-8");  
		PrintWriter writer = response.getWriter();
		writer.append(jsonString);
		writer.close();
		
		
		//request.getRequestDispatcher("/successLanding.jsp?num="+num).forward(request, response);
		} catch (Exception e) { 
		e.printStackTrace(); 
		} 

		
	}

<form action="${pageContext.request.contextPath}/addTextServlet" method="post">
<input type="hidden" id='textID' name='textID' value='<%=date%>'>
<input type="hidden" id='userID' name='userID' value='<%=userID%>'>
<input type="text" name="title" />
<input type="text" name="text" />
<input type="hidden" id='f1picpath' name='picpath1' value=''>
<input type="hidden" id='f2picpath' name='picpath2' value=''>

<button type="submit" id="uploadpic">上传文章</button>
</form>

这个表单是输入文字信息的表单,信息填写完之后,把图片的信息一同提交到后台的servlet。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int  userID=Integer.parseInt((String)request.getParameter("userID"));
		BigInteger textID=new BigInteger((String)request.getParameter("textID"));
		String title=request.getParameter("title");
		String text=request.getParameter("text");
		String picpath1=request.getParameter("picpath1");
		String picpath2=request.getParameter("picpath2");
//		String username=request.getParameter("username");
		String username="111";
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
		String date=sdf2.format(new Date()); 
		
		System.out.println("here 1");
		String message="how";
		int num_like=0;
		shareText text2=new shareText(userID, textID, title, text, picpath1, picpath2, username, date, num_like, message);
		if(title!=null&&text!=null) {
			System.out.println("here 2");
			SqlSession sqlSession=null;
			try {
				DataConnection connection=new DataConnection();
				sqlSession=connection.getSession();
				StudentMapper mapper=connection.getStudentMapper(sqlSession);
//				int a=mapper.updateText(title, text, username, date);
//				mapper.addText(userID, textID, title, text, picpath1, picpath2, username, date, num_like, message);
				mapper.addShareText(text2);
				System.out.println("here 3");
				sqlSession.commit();
				System.out.println("here 4");
				
					request.getRequestDispatcher("/successLanding.jsp").forward(request, response);
				
			}catch (Exception e) {
				System.out.println("inserttext has error");
			}
			
			finally {
				if(sqlSession!=null) {
					sqlSession.close();
				}
				
			}
			
			
		}
		
		
		
	}

后台接收参数之后,即可向数据库插入记录。

为什么需要这么做呢

减少用户对数据库读取次数,减少数据库的负担
因为图片上传到tomcat服务器目录下,并没有直接把路径存入数据库,而是等到把文字信息填写完之后,提交表单的时候,和文字信息一块存入数据库。

实现图片的预览和重新选择功能
因为通过ajax异步上传图片,图片可以直接上传到tomcat目录下,这里需要注意一点就是,tomcat服务器为了安全,默认是不能读取绝对路径的图片,所以,要想预览,只有上传到tomcat服务器才可以预览,为了减少用户误操作选择错误的图片,我们可以通过重现选择功能,即写一个方法,触发input输入框的即可。即代码中的click()方法可以模拟鼠标点击,触发input输入框进行选择图片。
在重新选择图片之后,需要把之前的图片子元素删除,否则会在原来的图片的基础之上,增加一个图片元素,破坏预期效果。empty()可以实现删除被选择元素的子元素。
然后,为了节约服务器的存储空间,我们需要通过一步方法,把之前的图片删除。

下面是删除文件的代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username="一旬";
		String picpath=request.getParameter("picpath");
		System.out.println(picpath);
		String fileName=picpath.substring(picpath.lastIndexOf("\\")+1);
		System.out.println(picpath);
		ServletContext sctx = getServletContext(); 
		String path = sctx.getRealPath("/images"); 
		File file = new File(path+"\\"+username+"\\"+fileName);
		if(file.exists()) {
			file.delete();
			System.out.println("success delete");
			String jsonString = JSON.toJSONString(picpath);  
			response.setCharacterEncoding("UTF-8");  
			response.setContentType("application/json; charset=utf-8");  
			PrintWriter writer = response.getWriter();
			writer.append(jsonString);
			writer.close();
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值