欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jsp+ajax实现无刷新上传文件的方法

程序员文章站 2022-04-15 10:14:25
本文实例讲述了jsp+ajax实现无刷新上传文件的方法。分享给大家供大家参考,具体如下: 列表页:selectaddress.jsp js页:ajax_edit.js...

本文实例讲述了jsp+ajax实现无刷新上传文件的方法。分享给大家供大家参考,具体如下:

列表页:selectaddress.jsp
js页:ajax_edit.js
jsp处理页:editaddress.jsp
上传工具类:uploadutil.java

jsp+ajax实现无刷新上传文件的方法

思想:由于安全问题,javascript操纵不了文件, 导致ajax不能动态上传文件,所以选择了iframe,

列表页把form表单提交到一个隐式的iframe里面,设置表单的属性

复制代码 代码如下:
enctype='multipart/form-data'  target='hidden_frame'

然后,处理页处理后返回
复制代码 代码如下:
out.println('<script>parent.callback(" 返回值 ")</script>');

列表页执行回调函数!

selectaddress.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<%@ page import="com.wap3.navigater.service.*" %>
<%@ page import="com.wap3.navigater.dao.*" %>
<%@ page import="com.wap3.navigater.pojo.*" %>
<%@ page import="com.wap3.navigater.util.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/ajax_edit.js"></script>
<script type="text/javascript" src="../js/jquery.jclock.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../js/jquery.form.js"></script>
<script type="text/javascript" src="../js/filetypejudge.js"></script>
<script type="text/javascript" src="../js/jquery.datepick.js"></script>
<script type="text/javascript" src="../js/jquery.datepick-zh-cn.js"></script>
<link media=all href="../css/common.css" type=text/css rel=stylesheet>
<title>insert title here</title>
<style type="text/css">
 @import "inc/jquery.datepick.css";
</style>
<script type="text/javascript">
var $imgthis;
 $(function(){
  var oldvalue;
  $(".package_list .edit").bind("dblclick",function(){
   oldvalue = $(this).text();
   $(this).ajax_edit("editaddress.jsp",oldvalue);
  });
  $(".package_list .edit_img").bind("dblclick",function(){ //
   oldvalue = $(this).html();
   $imgthis = $(this);
   $(this).parents("tr.package_list").siblings(".package_list").find(":input.cancel").trigger("click");
   $(this).ajax_edit_img("editaddress.jsp",oldvalue);
  });
  $(".package_list .edit :input[type!=file]:visible").live("blur",function(){
   $(this).ajax_handle("editaddress.jsp?action=edit",oldvalue);
  });
  $("#editcategoryname").live("change",function(){
   $(this).ajax_handle("editaddress.jsp?action=edit",oldvalue);
  });
  $("#del").click( function () {
   if($(":checkbox.urlid:checked").size()>0){
    var result = confirm("不可恢复的操作:确定要吗?"+ '\n' +"提示:如果删除大类会删除大类及下面的子类!!!");
    if (result) {
     var url = location.href;
     alert(url);
     return ;
     $(".main_table").wrap("<form id='selectaddressform' action='selectaddress.jsp?action=del' method='post'></form>");
     $("#selectaddressform").submit();
    }
   }else{
    alert("请选择要删除的项目!");
    return false;
   }
  });
 });
 function callback(msg) //处理jsp回调 过来的参数
 {
  $imgthis.html("<img class='logo' src='"+msg+"' title='"+msg+"' />");
 }
</script>
</head>
<body>
 <%
  string action = parameterutil.getstringparameter(request,"action","");
  friendurldao friendurldao = new ibatisfriendurldao();
  if("del".equals(action)){
   int[] urlids = parameterutil.getintarrayparams(request,"urlid");
   for(int urlid : urlids){
    friendurldao.deletefriendurlbyp(urlid);
   }
  }
  string navigaterpage = request.getrequesturl().tostring();
  if(request.getquerystring()!= null){
   navigaterpage += "?"+request.getquerystring();
  }
  int categoryid = parameterutil.getintparameter(request,"categoryid",0);
  if(categoryid == 0){
   response.sendredirect("selectcategory.jsp");
   return;
  }
  int pagesize = parameterutil.getintparameter(request,"pagesize",10);
  int pageno = parameterutil.getintparameter(request,"pageno",1);
  string orderby = parameterutil.getstringparameter(request,"orderby","sequence");
  int ascordesc = parameterutil.getintparameter(request,"ascordesc",0);
  categorydao categorydao = new ibatiscategorydao();
  category category = categorydao.selectcategorybyp(categoryid);
  string categoryname = category.getcategoryname();
  friendurl friendurl = new friendurl();
  friendurl.setcategoryid(categoryid);
  friendurl.addorderby(orderby,ascordesc);
  list<friendurl> friendurllist = friendurldao.selectfriendurlbye(friendurl);
   //分页
  int totallpage = (int) math.ceil(((double) friendurllist .size() * 1.0d)/ (double) pagesize);
  pageno =pageno <= 0 ? 1 : pageno;
  pageno =pageno > totallpage ? totallpage : pageno;
  datapageutil datepage = new datapageutil(friendurllist ,friendurllist .size(),pagesize, pageno);
  boolean hasprerpage = datepage.hasprevpage();
  boolean hasnextpage= datepage.hasnextpage();
  int curpageno = datepage.getpageno();
  int pagecount = datepage.getpagecount();
  friendurllist = datapageutil.sublist(friendurllist, pagesize, pageno);
  if(friendurllist == null && friendurllist.size()<=0) {
   out.println("没有您需要的数据");
  }else{
  %>
  <%@include file="inc/header.jsp" %>
 <div id = "mainbox">
  <div class = "c1">
   <table class="main_table" width="100%" border="1" cellspacing="0" cellpadding="0">
    <tr>
     <th align="center" height="20" colspan="13" align="center" bgcolor="#006699">条目列表</th>
    </tr>
    <tr>
     <td width="10%" height="20" align="center" bgcolor="#009999">
      <input id="allornoall" type="checkbox"><label for="allornoall">全选</label>
      <input type="button" id="reserse" value="反选" />
     </td>
     <td width="7%" height="20" align="center" bgcolor="#009999">站点名称</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">站点别名</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">归类</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">公司地址</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">文字链接</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">图片链接</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">描述</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">有效开始时间</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">有效结束时间</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">电话</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">位置排序</td>
     <td width="7%" height="20" align="center" bgcolor="#009999">推荐序号</td>
    </tr>
    <%
     for(friendurl friendurltemp:friendurllist) {
      int urlid = friendurltemp.geturlid();
      string sitename = friendurltemp.getsitename();
      string alias = friendurltemp.getalias();
      string address = friendurltemp.getaddress();
      string texturl = friendurltemp.gettexturl();
      string imageurl = friendurltemp.getimageurl();
      string description = friendurltemp.getdescription();
      date validbegintime = friendurltemp.getvalidbegintime();
      date validendtime = friendurltemp.getvalidendtime();
      string mobile = friendurltemp.getmobile();
      int sequence = friendurltemp.getsequence();
      int filter = friendurltemp.getfilter();
     %>
    <tr class="package_list">
     <td height="20" align="center" class="urlid_td"><input type="checkbox" name="urlid" class="id_select urlid" value=<%= urlid%> /></td>
     <td height="20" align="center" class="edit sitename"><%=sitename %></td>
     <td height="20" align="center" class="edit alias"><%=alias %></td>
     <td height="20" align="center" class="edit categoryname"><%=categoryname%></td>
     <td height="20" align="center" class="edit address"><%=address %></td>
     <td height="20" align="center" class="edit texturl"><%=texturl%></td>
     <td height="20" align="center" class="edit_img imageurl"><img src='<%=imageurl%>' class='logo' title='<%=imageurl%>'/></td>
     <td height="20" align="center" class="edit description"><%=description%></td>
     <td height="20" align="center" class="edit validbegintime"><%=validbegintime == null || "".equals(validbegintime)? "--:--" : timeutil.date2str(validbegintime)%></td>
     <td height="20" align="center" class="edit validendtime"><%=validendtime == null || "".equals(validendtime)? "--:--" : timeutil.date2str(validendtime)%></td>
     <td height="20" align="center" class="edit mobile"><%=mobile%></td>
     <td height="20" align="center" class="edit sequence"><%=sequence%></td>
     <td height="20" align="center" class="edit filter"><%=filter%></td>
    </tr>
    <%
     }
     %>
    <tr>
     <td align="center"><input type="button" id="del" value="删除" /></td>
     <td align="center" colspan = "12">提示:双击选框修改属性值</td>
    </tr>
   </table>
  </div>
  <%@ include file="inc/pagination.jsp"%>
 </div>
 <%
  }
  %>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</body>
</html>

editaddress.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<%@ page import="com.wap3.navigater.util.*" %>
<%@ page import="com.wap3.navigater.service.*" %>
<%@ page import="com.wap3.navigater.pojo.*" %>
<%@ page import="com.wap3.navigater.dao.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
 <%
  string target = parameterutil.getstringparameter(request,"target","");
  string action = parameterutil.getstringparameter(request,"action","");
  if(!"".equals(target) && target != null && "edit".equals(action)){
   int categoryid = 0;
   categorydao categorydao = null;
   int urlid=0,status=0,sequence=0,filter=0;
   string sitename=null,alias=null,texturl=null,imageurl=null,description=null,mobile=null;
   date validbegintime=null,validendtime=null;
   if("imageurl".equals(target)){
    system.out.println("图片上传");
    uploadutil.upload(request, response);
    string imageurlpath = (string) request.getattribute("imageurlpath");
    urlid = integer.parseint((string)request.getattribute("urlid"));
    imageurl = (string)request.getattribute("imageurlpath");
   }else{
    if("categoryname".equals(target)){
     string categoryname = parameterutil.getstringparameter(request,"categoryname","");
     category category = new category();
      category.setcategoryname(categoryname);
     categorydao = new ibatiscategorydao();
     category category2 = categorydao.selectcategorybye(category).get(0);
      categoryid = category2.getcategoryid();
    }else{
     categoryid = parameterutil.getintparameter(request,"categoryid",0);
    }
     urlid = parameterutil.getintparameter(request,"urlid",0);
     sitename = parameterutil.getstringparameter(request,"sitename","");
     alias = parameterutil.getstringparameter(request,"alias","");
     texturl = parameterutil.getstringparameter(request,"texturl","");
     imageurl = parameterutil.getstringparameter(request,"imageurl","");
     description = parameterutil.getstringparameter(request,"description","");
     status = parameterutil.getintparameter(request,"status",0);
     sequence = parameterutil.getintparameter(request,"sequence",0);
     filter = parameterutil.getintparameter(request,"filter",0);
     mobile = parameterutil.getstringparameter(request,"mobile","");
     validbegintime = parameterutil.getdateparameter(request,"validbegintime");
     validendtime = parameterutil.getdateparameter(request,"validendtime");
   }
   calendar beginday=calendar.getinstance();
   friendurl friendurl = new friendurl();
    friendurl.seturlid(urlid);
    friendurl.setsitename(sitename);
    friendurl.setdescription(description);
    friendurl.settexturl(texturl);
    friendurl.setimageurl(imageurl);
    friendurl.setalias(alias);
    friendurl.setsequence(sequence);
    friendurl.setmobile(mobile);
    friendurl.setcategoryid(categoryid);
    friendurl.setstatus(status);
    friendurl.setvalidbegintime(validbegintime);
    friendurl.setvalidendtime(validendtime);
    friendurl.setfilter(filter);
   friendurldao friendurldao = new ibatisfriendurldao();
   friendurldao.updatefriendurlbyp(friendurl);
   friendurl friendurl2 = friendurldao.selectfriendurlbye(friendurl).get(0);
   if(friendurl2 != null){
    string methodname = "get" + target.substring(0,1).touppercase()+target.substring(1);
    if(target.endswith("time")){
     simpledateformat df = new simpledateformat("yyyy-mm-dd");
     out.println(timeutil.date2str(((date)(friendurl2.getclass().getmethod(methodname,new class[]{}).invoke(friendurl2,new object[]{})))));
    }else if("categoryname".equals(target)){
     out.println(categorydao.selectcategorybyp(friendurl2.getcategoryid()).getcategoryname());
    }else if("imageurl".equals(target)){
     // 无刷新关键的步骤,让iframe的父辈body执行callback这个函数
     out.println("<script>parent.callback('"+friendurl2.getclass().getmethod(methodname,new class[]{}).invoke(friendurl2,new object[]{})+"')</script>");
    }else{
     out.println(friendurl2.getclass().getmethod(methodname,new class[]{}).invoke(friendurl2,new object[]{}));
    }
   }else{
    out.println("更新失败");
   }
  }
%>

ajax_edit.js

(function(){
  $.fn.extend({
   ajax_edit:function(str,oldvalue){
    return this.each(function(){
     $this = $(this);
     var id;
     var nameid = $this.attr("class").split(" ")[1];
     var idname = $this.parents("tr.package_list").find("td:first-child :input[type=checkbox]").attr("class").split(" ")[1];
     id = $this.siblings("."+idname+"_td").find("input").val();
     if(nameid == "categoryname" && str == "editaddress.jsp"){
      $this.load("categorylist.jsp",{'oldvalue':oldvalue,'urlid':id});
     }else{
      $this.html("<form id='selectaddressform'><input type='hidden' name='"+idname+"' value='"+id+"' /><input type='hidden' name='target' value='"+nameid+"' /><input type='text' name='"+nameid+"' value='"+oldvalue+"'/></form>");
      $this.find(":input:last").focus();
     }
    })
   },
  ajax_edit_img:function(str,oldvalue){ //处理图片上传ajax 关键的一步form表格里的 target='hidden_frame'提交到id为hidden_frame的iframe里面
   return this.each(function(){
    var $this = $(this);
    var nameid = $this.attr("class").split(" ")[1];
    var idname = $this.parents("tr.package_list").find("td:first-child :input[type=checkbox]").attr("class").split(" ")[1];
    var id = $this.siblings("."+idname+"_td").find("input").val();
    var $imgform = $("<form id='selectaddressform_img' action='editaddress.jsp?action=edit&target=imageurl' method='post' enctype='multipart/form-data' target='hidden_frame'><input type='hidden' name='"+idname+"' value='"+id+"' /><input type='file' name='"+nameid+"' /><input type='button' class='cancel' value='取消' /><input type='button' class='ok' value='上传' /></form>");
    $this.html($imgform);
    $this.find(":input:last").focus();
    $imgform.find(":input[type=file]").bind("change",function(){
     $(this).filetypejudge("photo");
    })
    $imgform.find(":input.ok").bind("click",function(){
     var $button = $(this);
     if($imgform.find(":input[type=file]").val()==''){
      alert("请上传图片!");
      return false;
     }
     $button.attr("disabled",true);
     $("#selectaddressform_img").submit();
    })
    $imgform.find(":input.cancel").bind("click",function(){
     $(this).parents(".edit_img").html(oldvalue);
    });
   })
  },
  ajax_handle:function(str,oldvalue){
    return this.each(function(){
     var $this = $(this);
     settimeout(function(){
     if(!$("div").hasclass("datepick-control") || !$("div .datepick-control").is(":visible")){
      if(oldvalue != $this.val() && $this.val() !="" ){
         $.post(
          str,$("#selectaddressform").serialize(),
          function(data){
           $this.parents(".edit").text(data.trim()).css("color","red");
          }
         )
      }else{
       $this.parents(".edit").text(oldvalue);
      }
     }
     },1000);
    })
   }
  })
})(jquery)

希望本文所述对大家ajax程序设计有所帮助。