Springmvc下一次选多个文件上传(二)Ajax异步

来源:互联网 发布:华中科技大学网络大专 编辑:程序博客网 时间:2024/06/06 19:10

通过Ajax异步一次选中多个图片上传:

springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!-- 自动扫描包下面的文件,类上带有@Controller的会注册为bean --><context:component-scan base-package="com.taray.controller"></context:component-scan><!-- 代替处理器映射器、处理器适配器 ,mvc注解驱动--><mvc:annotation-driven/><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 配置jsp路径的前缀,后缀,那样在controller中设置视图时候不需要再加了 --><!-- prefix前缀如果 不添加,那么如果在@controller注解下有一个@requestmapping("name")访问时候会出错--><property name="prefix" value="/"/><property name="suffix" value=".jsp"/></bean> <!-- Spring MVC上传文件时,我们都需要配置一个MultipartResolver的实现, 常用的是Apache提供的CommonsMultipartResolver类 --> <!-- Spring MVC的核心类DispatcherServlet中, 把这些bean的id固定了. 你必须保证bean的id相同, 才能正常工作.  -->      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <property name="defaultEncoding" value="UTF-8"/>      <!--max size: 10M 1024*1024*10-->      <property name="maxUploadSize" value="10485760"/>      </bean>  </beans>
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  <%    String path = request.getContextPath();    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>      <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.4.min.js"></script>      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      <title>Index2</title>      <script type="text/JavaScript" src="http://apps.bdimg.com/libs/jQuery/1.6.4/jquery.min.js"></script>      <link href="http://libs.baidu.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">      <script src="http://libs.baidu.com/bootstrap/2.3.2/js/bootstrap.min.js"></script>      <script src="js/upload.js"></script>  </head>    <body>   <input type="text" name="plprourls" id="d_plpic" readonly><button type="button" class="btn btn-warning" onclick="plxtpsc(this,'d_plpic')">选择图片</button><input type="file" style="display: none;"  name="fileToPic" id="fileToPic" multiple="multiple">  </body><script type="text/javascript">var ink=new Object();ink.home="<%=basePath%>";</script>         </html>  

upload.js

jQuery.extend({createUploadIframe:function(id,uri){var main="jUploadFrame"+id;var html="<iframe style='position:absolute;top:-9999px;left:-9999px;' name='"+main+"' id='"+main+"'";if(window.ActiveXObject){if(typeof uri=="boolean"){html+=" src='javascript:;'";}else if(typeof uri=="string"){html+=" src='"+uri+"'";}}html+="/>";jQuery(html).appendTo(document.body);return jQuery("#"+main).get(0);},createUploadForm:function(id,eid,data){var main="jUploadForm"+id;var file="jUploadFile"+id;var form=jQuery("<form action='' method='POST' enctype='multipart/form-data' name='"+main+"' id='"+main+"'></form>");if(data){for(var i in data){jQuery("<input type='hidden' value='"+data[i]+"' name='"+i+"'/>").appendTo(form);}}var e0=jQuery("#"+eid);var e1=jQuery(e0).clone();jQuery(e0).attr("id",file);jQuery(e0).before(e1);jQuery(e0).appendTo(form);jQuery(form).css("position","absolute");jQuery(form).css("top","-1200px");jQuery(form).css("left","-1200px");jQuery(form).appendTo("body");return form;},ajaxFileUpload:function(s){s=jQuery.extend({},jQuery.ajaxSettings,s);var id=new Date().getTime();var form=jQuery.createUploadForm(id,s.fileElementId,typeof s.data=="undefined"?false:s.data);var io=jQuery.createUploadIframe(id,s.secureuri);var main="jUploadFrame"+id;var formId="jUploadForm"+id;if(s.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart");}var xml={};var done=false;if(s.global){jQuery.event.trigger("ajaxSend",[xml,s]);}var todo=function(out){var io=document.getElementById(main);try{if(io.contentWindow){xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}else if(io.contentDocument){xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;}}catch(e){jQuery.handleError(s,xml,null,e);}if(xml||out=="timeout"){done=true;var status=null;try{status=out!="timeout"?"success":"error";if(status!="error"){var data=jQuery.uploadHttpData(xml,s.dataType);if(s.success){s.success(data,status);}if(s.global){jQuery.event.trigger("ajaxSuccess",[xml,s]);}}else{jQuery.handleError(s,xml,status);}}catch(e){status="error";jQuery.handleError(s,xml,status,e);}if(s.global){jQuery.event.trigger("ajaxComplete",[xml,s]);}if(s.global&&!--jQuery.active){jQuery.event.trigger("ajaxStop");}if(s.complete){s.complete(xml,status);}jQuery(io).unbind();window.setTimeout(function(){try{jQuery(io).remove();jQuery(form).remove();}catch(e){jQuery.handleError(s,xml,null,e);}},100);xml=null;}}if(s.timeout>0){window.setTimeout(function(){if(!done){todo("timeout");}},s.timeout);}try{var form=jQuery("#"+formId);jQuery(form).attr("action",s.url);jQuery(form).attr("method","POST");jQuery(form).attr("target",main);jQuery(form).attr(form.encoding?"encoding":"enctype","multipart/form-data");jQuery(form).submit();}catch(e){jQuery.handleError(s,xml,null,e);}jQuery("#"+main).load(todo);return {abort:function(){}};},uploadHttpData:function(r,type){var data=!type||type=="xml"?r.responseXML:r.responseText;data=data.substring(data.indexOf("@@@@@")+5,data.indexOf("#####"));if(type=="script"){jQuery.globalEval(data);}else if(type=="json"){}else if(type=="html"){jQuery("<div>").html(data).evalScripts();}return data;}});//批量上传图片function plxtpsc(obj,id){$("#fileToPic").click();$("#fileToPic").change(function(e){$.ajaxFileUpload({url:ink.home+"upload.htm",secureuri:false,fileElementId:"fileToPic",dataType:"text",success:function(data,status){$("#"+id).val(data);$("#fileToPic").val('');}});});}

UploadController.java

package com.taray.controller;import java.io.File;import java.util.List;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;@Controller@Scope("prototype")public class UploadController {@RequestMapping("load")public String loadJsp(){return "index";}@RequestMapping("upload")public String uploadfile(HttpServletRequest request,HttpServletResponse response) throws Exception{String field="fileToPic";MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;List<MultipartFile> filelist=multipartRequest.getFiles(field);        for(MultipartFile multipartFile:filelist){        //***此处执行上传到服务器,我这儿就是上传到本地此项目在Tomcat下的根目录中***            //文件的原始名称            String originalFilename=multipartFile.getOriginalFilename();            String newFileName=null;            if (multipartFile!=null&&originalFilename!=null&&originalFilename.length()>0){                newFileName= UUID.randomUUID()+originalFilename;                //存储图片的物理路径                String pic_path = request.getSession().getServletContext().getRealPath("/upload");                //如果文件夹不存在则创建                File file=new File(pic_path);                if(!file.exists()){                System.out.println("file not exists");                file.mkdir();                }                /**                 * 获取新文件的File实例,通过spring的org.springframework.web.multipartInterface MultipartFile                 * 下的transferTo方法,这个可以移动文件的文件系统,复制文件系统中的文件或内存内容保存到目标文件.                 * 如果目标文件已经存在,它将被删除。                 */                //新文件路径实例                File targetFile = new File(pic_path, newFileName);                //内存数据读入磁盘                multipartFile.transferTo(targetFile);            }        }        String resultStr="此处可以是图片的线上路径";        //这@#是upload.js中加的一个判断使用        response.getWriter().write("@@@@@"+resultStr+"#####");return null;}}










0 0
原创粉丝点击