SpringMVC上传下载,页面不刷新提交带附件的form表单

周所周知,如果要提交的form表单内带有附件,那么需要设置属性enctype="multipart/form-data"

当我们要实现页面不刷新提交form表单的时候需要用到ajax,但是ajax提交form表单的时候需要将表单值进行序列化操作($(formId).formSerialize())。

所以问题出现了,表单序列化后form表单内的文件在后台就接不到了。

所以带有附件的form表单不能用ajax提交。既然我们要实现页面不刷新,那就需要模拟ajax进行提交form表单。   

我是用隐藏的iframe实现的:

前提条件:

springmvc配置文件中加上     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> 

需要jar包:ant-1.6.5.jar;commons-fileupload-1.2.2.jar;commons-io-2.0.1.jar

代码示例:

上传文件jsp页面:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <form  id="form2"  name="form2"   target="hidden_frame" enctype="multipart/form-data"  method="post" >        
  2.     <!--two end-->    
  3.           
  4.          <h4 class="title_bg_b">  
  5.               <span class="title_left">软件升级</span>  
  6.          </h4>  
  7.          <ul class="form_list_ul clear">  
  8.                <li class="clear">      
  9.                    <span class="list_li_span">软件安装包:</span>     
  10.                    <input type="file"   id="file1"  name="file1"/>  
  11.                     <input type="button"  name="button2"  onclick="uploadFile()" class="blue_btn" value="上传" /><span id="msgspan"></span>  
  12.                     <input type="button"  name="button2" id="shengji" class="blue_btn" onclick="Upgrade()" title="正在实现" value="升级" />  
  13.                           
  14.                </li>  
  15.          </ul>    
  16. </form>          
  17. <iframe name='hidden_frame' id="hidden_frame" style='display:none' width="99%"></iframe>  

js函数:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function createPrompt(info){  
  2.     var msgw,msgh,bordercolor;  
  3.     msgw=400;//提示窗口的宽度  
  4.     msgh=100;//提示窗口的高度  
  5.     titleheight=25//提示窗口标题高度  
  6.     bordercolor="#336699";//提示窗口的边框颜色  
  7.     titlecolor="#99CCFF";//提示窗口的标题颜色  
  8.     var sWidth,sHeight;  
  9.     sWidth=document.body.offsetWidth;//浏览器工作区域内页面宽度 或使用 screen.width//屏幕的宽度  
  10.     sHeight=screen.height;//屏幕高度(垂直分辨率)  
  11.     //背景层(大小与窗口有效区域相同,即当弹出对话框时,背景显示为放射状透明灰色)  
  12.     var bgObj=document.createElement("div");//创建一个div对象(背景层) //动态创建元素,这里创建的是 div  
  13.     //定义div属性,即相当于(相当于,但确不是,必须对对象属性进行定义  
  14.     //<div id="bgDiv" style="position:absolute; top:0; background-color:#777; filter:progid:DXImagesTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75); opacity:0.6; left:0; width:918px; height:768px; z-index:10000;"></div>  
  15.     bgObj.setAttribute('id','bgDiv');  
  16.     bgObj.style.position="absolute";  
  17.     bgObj.style.top="0";  
  18.     bgObj.style.background="#777";  
  19.     bgObj.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75";  
  20.     bgObj.style.opacity="0.6";  
  21.     bgObj.style.left="0";  
  22.     bgObj.style.width=sWidth + "px";  
  23.     bgObj.style.height=sHeight + "px";  
  24.     bgObj.style.zIndex = "10000";  
  25.     document.body.appendChild(bgObj);//在body内添加该div对象  
  26.     //创建一个div对象(提示框层)  
  27.     var msgObj=document.createElement("div")  
  28.     //定义div属性,即相当于  
  29.     //<div id="msgDiv" align="center" style="background-color:white; border:1px solid #336699; position:absolute; left:50%; top:50%; font:12px/1.6em Verdana,Geneva,Arial,Helvetica,sans-serif; margin-left:-225px; margin-top:npx; width:400px; height:100px; text-align:center; line-height:25px; z-index:100001;"></div>  
  30.     msgObj.setAttribute("id","msgDiv");  
  31.     msgObj.setAttribute("align","center");  
  32.     msgObj.style.background="white";  
  33.     msgObj.style.border="1px solid " + bordercolor;  
  34.     msgObj.style.position = "absolute";  
  35.     msgObj.style.left = "50%";  
  36.     msgObj.style.top = "50%";  
  37.     msgObj.style.font="12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif";  
  38.     msgObj.style.marginLeft = "-225px" ;  
  39.     msgObj.style.marginTop = -75+document.documentElement.scrollTop+"px";  
  40.     msgObj.style.width = msgw + "px";  
  41.     msgObj.style.height =msgh + "px";  
  42.     msgObj.style.textAlign = "center";  
  43.     msgObj.style.lineHeight ="25px";  
  44.     msgObj.style.zIndex = "10001";  
  45.       
  46.     document.body.appendChild(msgObj);//在body内添加提示框div对象msgObj  
  47.     var txt=document.createElement("p");//创建一个p对象(提示框提示信息)  
  48.     //定义p的属性,即相当于  
  49.     //<p style="margin:1em 0;" id="msgTxt">测试效果</p>  
  50.     txt.style.margin="1em 0"  
  51.     txt.setAttribute("id","msgTxt");  
  52.     txt.innerHTML=info;//来源于函数调用时的参数值  
  53.     document.getElementById("msgDiv" ).appendChild(txt);//在提示框div中添加提示信息对象txt  
  54.   
  55.     var img=document.createElement("img");  
  56.     img.src="/resources/images/waiting.gif";  
  57.     img.style.width="150";  
  58.     img.style.height="25";  
  59.     img.style.align="center";  
  60.     document.getElementById("msgDiv").appendChild(img);  
  61. }  


后台控制类:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bohui.ipview.common;  
  2. import javax.servlet.http.HttpServletRequest;  
  3. import javax.servlet.http.HttpServletResponse;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.servlet.ModelAndView;  
  8. import com.bohui.ipview.bean.FileUploadBean;  
  9. /** 
  10.  *  
  11.  * @author caohaicheng 
  12.  * @date 2014-3-20 上午11:56:35 
  13.  */  
  14. @Controller  
  15. @RequestMapping(value = "fileOperate")  
  16. public class FileOperateController {  
  17.     /** 
  18.      * 上传文件 
  19.      *  
  20.      * @author caohaicheng 
  21.      * @date 2014-3-20 上午11:56:35 
  22.      * @param request 
  23.      * @return 
  24.      * @throws Exception 
  25.      */  
  26.     @RequestMapping(value = "upload1")  
  27.     public ModelAndView  upload(HttpServletRequest request) throws Exception {  
  28.         ModelAndView mv=new ModelAndView("sysconfig/fileUploadResult");  
  29.         FileUploadBean fup  = new FileUploadBean();  
  30.         fup=FileOperateUtil.upload(request );  
  31.           
  32.         mv.addObject("fileName",fup.getFileName() );  
  33.         mv.addObject("fileSize",fup.getFileSize() );  
  34.         mv.addObject("FileCreateDate", fup.getFileCreateDate());  
  35.         mv.addObject("returnDesc", fup.getReturnDesc());  
  36.         mv.addObject("returnFlag",fup.getReturnFlag() );  
  37.         return mv;  
  38.     }  
  39.   
  40.     /** 
  41.      * 下载 
  42.      *  
  43.      * @author caohaicheng 
  44.      * @date 2014-3-20 上午11:56:35 
  45.      * @param attachment 
  46.      * @param request 
  47.      * @param response 
  48.      * @return 
  49.      * @throws Exception 
  50.      */  
  51.     @RequestMapping(value = "download")  
  52.     public ModelAndView download(HttpServletRequest request,  
  53.             HttpServletResponse response) throws Exception {  
  54.   
  55.         String storeName = "201205051340364510870879724.zip";  
  56.         String realName = "Java设计模式.zip";  
  57.         String contentType = "application/octet-stream";  
  58.   
  59.         FileOperateUtil.download(request, response, storeName, contentType,  
  60.                 realName);  
  61.   
  62.         return null;  
  63.     }  
  64. }  

实现类:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bohui.ipview.common;  
  2. import java.io.BufferedInputStream;  
  3. import java.io.BufferedOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.Iterator;  
  9. import java.util.Map;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import org.springframework.util.FileCopyUtils;  
  13. import org.springframework.web.multipart.MultipartFile;  
  14. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  15. import com.bohui.ipview.bean.FileUploadBean;  
  16. import com.bohui.ipview.util.DateTimeUtil;  
  17. /** 
  18.  *  
  19.  * @author caohaicheng 
  20.  * @date 2014-3-20 上午11:56:35 
  21.  */  
  22. public class FileOperateUtil {  
  23.     private static final String UPLOADDIR = "/bh/update/";// 上传后放在哪个位置(linux)  
  24.     private static final String UPLOADDIR1 = "/bh/backup/";// 上传后放在哪个位置(linux)  
  25.   
  26.     /** 
  27.      * 将上传的文件进行重命名 
  28.      *  
  29.      * @author caohaicheng 
  30.      * @date 2014-3-20 上午11:56:35 
  31.      * @param name 
  32.      * @return 
  33.      */  
  34.     private static String rename(String name) {  
  35.   
  36.         Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")  
  37.                 .format(new Date()));  
  38.         Long random = (long) (Math.random() * now);  
  39.         String fileName = now + "" + random;  
  40.   
  41.         if (name.indexOf(".") != -1) {  
  42.             fileName += name.substring(name.lastIndexOf("."));  
  43.         }  
  44.   
  45.         return fileName;  
  46.     }  
  47.   
  48.     /** 
  49.      * 压缩后的文件名 
  50.      *  
  51.      * @author caohaicheng 
  52.      * @date 2014-3-20 上午11:56:35 
  53.      * @param name 
  54.      * @return 
  55.      */  
  56.     private static String zipName(String name) {  
  57.         String prefix = "";  
  58.         if (name.indexOf(".") != -1) {  
  59.             prefix = name.substring(0, name.lastIndexOf("."));  
  60.         } else {  
  61.             prefix = name;  
  62.         }  
  63.         return prefix + ".zip";  
  64.     }  
  65.   
  66.     /** 
  67.      * 上传文件 
  68.      *  
  69.      * @author caohaicheng 
  70.      * @date 2014-3-20 上午11:56:35 
  71.      * @param request 
  72.      * @param params 
  73.      * @param values 
  74.      * @return 
  75.      * @throws Exception 
  76.      */  
  77.     public static FileUploadBean upload(HttpServletRequest request) throws Exception {  
  78.   
  79.         FileUploadBean fup  = new FileUploadBean();  
  80.           
  81.         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
  82.         Map<String, MultipartFile> fileMap = mRequest.getFileMap();  
  83.   
  84.         //String uploadDir = request.getSession().getServletContext().getRealPath("/")+ FileOperateUtil.UPLOADDIR;   //上传至相对路径  
  85.         String uploadDir =  FileOperateUtil.UPLOADDIR;  //上传至绝对路径  
  86.         String uploadDir1 =  FileOperateUtil.UPLOADDIR1;    //上传至绝对路径,这个是备份文件夹  
  87.           
  88.         File file = new File(uploadDir);  
  89.         File file1 = new File(uploadDir1);  
  90.   
  91.         //如果不存在该路径就创建  
  92.         if (!file.exists()) {  
  93.             file.mkdir();  
  94.         }  
  95.         if (!file1.exists()) {  
  96.             file1.mkdir();  
  97.         }  
  98.           
  99.          delAllFile(uploadDir); //删除完里面所有内容  
  100.   
  101.         String fileName = null;  
  102.         int i = 0;  
  103.         for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()  
  104.                 .iterator(); it.hasNext(); i++) {  
  105.   
  106.             Map.Entry<String, MultipartFile> entry = it.next();  
  107.             MultipartFile mFile = entry.getValue();  
  108.   
  109.             fileName = mFile.getOriginalFilename();//获得文件名字  
  110.   
  111.             //String storeName = rename(fileName);//对文件进行重命名  
  112.   
  113.             String noZipName = uploadDir + fileName;//文件路径  
  114.             String noZipName1 = uploadDir1 + fileName;  
  115.               
  116.             File uploadFile = new File(noZipName);     
  117.             File uploadFile1 = new File(noZipName1);     
  118.   
  119.             //String zipName = zipName(noZipName);//获得压缩后的文件名字  
  120.   
  121.             // 上传成为压缩文件  
  122.             /*           
  123.                 ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(noZipName))); 
  124.                 outputStream.putNextEntry(new ZipEntry(fileName)); 
  125.                 outputStream.setEncoding("GBK"); 
  126.                 FileCopyUtils.copy(mFile.getInputStream(), outputStream); 
  127.              */   
  128.                 try {  
  129.                     FileCopyUtils.copy(mFile.getBytes(), uploadFile);  
  130.                 } catch (Exception e) {  
  131.                     fup.setReturnDesc("升级文件上传失败");  
  132.                     fup.setReturnFlag(false);  
  133.                     e.printStackTrace();  
  134.                     return fup;  
  135.                 }     
  136.                   
  137.                 try {  
  138.                     FileCopyUtils.copy(mFile.getBytes(), uploadFile1);  
  139.                 } catch (Exception e) {  
  140.                     fup.setReturnDesc("升级文件备份失败");  
  141.                     fup.setReturnFlag(false);  
  142.                     e.printStackTrace();  
  143.                     return fup;  
  144.                 }     
  145.                 fup.setReturnFlag(true);  
  146.                 fup.setFileName(fileName);  
  147.                 fup.setFileCreateDate(DateTimeUtil.nowToString());  
  148.                 fup.setFileSize( new File(noZipName).length());  
  149.         }  
  150.         return fup;  
  151.     }  
  152.   
  153.     /** 
  154.      * 下载 
  155.      *  
  156.      * @author caohaicheng 
  157.      * @date 2014-3-20 上午11:56:35 
  158.      * @param request 
  159.      * @param response 
  160.      * @param storeName 
  161.      * @param contentType 
  162.      * @param realName 
  163.      * @throws Exception 
  164.      */  
  165.     public static void download(HttpServletRequest request,  
  166.             HttpServletResponse response, String storeName, String contentType,  
  167.             String realName) throws Exception {  
  168.         response.setContentType("text/html;charset=UTF-8");  
  169.         request.setCharacterEncoding("UTF-8");  
  170.         BufferedInputStream bis = null;  
  171.         BufferedOutputStream bos = null;  
  172.   
  173.         String ctxPath = request.getSession().getServletContext()  
  174.                 .getRealPath("/")  
  175.                 + FileOperateUtil.UPLOADDIR;  
  176.         String downLoadPath = ctxPath + storeName;  
  177.   
  178.         long fileLength = new File(downLoadPath).length();  
  179.   
  180.         response.setContentType(contentType);  
  181.         response.setHeader("Content-disposition""attachment; filename="  
  182.                 + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
  183.         response.setHeader("Content-Length", String.valueOf(fileLength));  
  184.   
  185.         bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
  186.         bos = new BufferedOutputStream(response.getOutputStream());  
  187.         byte[] buff = new byte[2048];  
  188.         int bytesRead;  
  189.         while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  190.             bos.write(buff, 0, bytesRead);  
  191.         }  
  192.         bis.close();  
  193.         bos.close();  
  194.     }  
  195.       
  196.     //删除指定文件夹下所有文件  
  197.     //param path 文件夹完整绝对路径  
  198.        public static boolean delAllFile(String path) {  
  199.            boolean flag = false;  
  200.            File file = new File(path);  
  201.            if (!file.exists()) {  
  202.              return flag;  
  203.            }  
  204.            if (!file.isDirectory()) {  
  205.              return flag;  
  206.            }  
  207.            String[] tempList = file.list();  
  208.            File temp = null;  
  209.            for (int i = 0; i < tempList.length; i++) {  
  210.               if (path.endsWith(File.separator)) {  
  211.                  temp = new File(path + tempList[i]);  
  212.               } else {  
  213.                   temp = new File(path + File.separator + tempList[i]);  
  214.               }  
  215.               if (temp.isFile()) {  
  216.                  temp.delete();  
  217.               }  
  218.               if (temp.isDirectory()) {  
  219.                  delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件  
  220.                  flag = true;  
  221.               }  
  222.            }  
  223.            return flag;  
  224.          }  
  225. }  


上传状态实体类:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.bohui.ipview.bean;  
  2. public class FileUploadBean {  
  3.     private String fileName;  
  4.     private Long fileSize;  
  5.     private String FileCreateDate;  
  6.     private String returnDesc;  
  7.     private Boolean returnFlag;  
  8.       
  9.       
  10.     public String getFileName() {  
  11.         return fileName;  
  12.     }  
  13.     public void setFileName(String fileName) {  
  14.         this.fileName = fileName;  
  15.     }  
  16.   
  17.     public String getFileCreateDate() {  
  18.         return FileCreateDate;  
  19.     }  
  20.     public void setFileCreateDate(String fileCreateDate) {  
  21.         FileCreateDate = fileCreateDate;  
  22.     }  
  23.     public String getReturnDesc() {  
  24.         return returnDesc;  
  25.     }  
  26.     public void setReturnDesc(String returnDesc) {  
  27.         this.returnDesc = returnDesc;  
  28.     }  
  29.     public Boolean getReturnFlag() {  
  30.         return returnFlag;  
  31.     }  
  32.     public void setReturnFlag(Boolean returnFlag) {  
  33.         this.returnFlag = returnFlag;  
  34.     }  
  35.     public long getFileSize() {  
  36.         return fileSize;  
  37.     }  
  38.     public void setFileSize(long l) {  
  39.         this.fileSize = l;  
  40.     }  
  41.   
  42.       
  43.       
  44. }  

子页面jsp文件fileUploadResult.jsp:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Insert title here</title>  
  8. <script  type="text/javascript">  
  9.     function parentTishi(){  
  10.         parent.tishi("${fileName}","${fileSize}","${FileCreateDate}","${returnDesc}","${returnFlag}");  
  11.     }  
  12. </script>  
  13. </head>  
  14.   
  15. <body onload="parentTishi()" >  
  16.     这里是上传文件的返回页面.....  
  17. </body>  
  18. </html>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值