码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc异步上传文件

时间:2017-07-27 20:20:30      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:nal   Enctype   color   multipart   文件名   size   https   enc   err   

前提条件

注意:bean的id名不能改变

<!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760" />
        <!--<property name="resolveLazily" value="true"/>-->
    </bean>

 

前台页面upload.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="${pageContext.request.contextPath }/static/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/jquery/jquery.form.js"></script>
    <script type="text/javascript">
   		//这种方式,可以异步请求数据,但是不能异步上传文件
   		/*使用这种方式,会在后台抛出一个异常:
   			org.springframework.web.multipart.MultipartException: 
   				The current request is not a multipart request
   		*/
   		function doUpload(){
   			$.ajax({  
   			     url : "getParamFromFile",  
   			     type : "POST",  
   			     data : $(‘#postForm‘).serialize(),  
   			     success : function(data) {  
   			          $( ‘#messageTip‘).html(data);
   			          $( ‘#messageTip‘).show();
   			     },  
   			     error : function(data) {  
   			          $( ‘#messageTip‘).html(data);
   			          $( ‘#messageTip‘).show();
   			     }  
   			}); 
   		} 
   		
   		//使用jquery.form.js的表单插件来提交表单,这个可以异步上传文件
   		/* function doUpload(){
   	   	    var options = {
   	   	    	url: ‘getParamFromFileForAjax‘,//表单提交的地址。缺省值: 表单的action的值
   	   	    	type: ‘POST‘,
   	   	    	dataType:‘text‘,
   	   	    	data :{
					fileName : ‘uploadFile‘   	   	    		
   	   	    	},
   	   	  		//clearForm: true,//成功提交后,清除所有表单元素的值
   	   	  		//timeout: 3000 ,//限制请求的时间,当请求大于3秒后,跳出请求
   	   	  		// 从服务传过来的数据显示在这个div内部也就是ajax局部刷新
   	   	    	//target: ‘#output1‘,
   	   	 		
   	   	  		// 处理之后的处理
   	   	  		success: function(data){
   	   	  			alert(data);
   	   	  			var result = $.parseJSON(data);
   	   	  			alert(result);
   	   	  		}
   	   	 	};
   	   	    
   	   	    //使用jquery的ajax upload插件可以上传文件
	   	   	$(‘#postForm‘).ajaxSubmit(options);
   		} */
    </script>
</head>
<body>
    <form id="postForm" action="getParamFromFile" method="post" 
		enctype="multipart/form-data">
	                上传XML模版文件:<input type="file" name="uploadFile"/>
	                <input type="submit" value="上传"/>
	      <input type="button" value="获取Json参数数据" onclick="doUpload()"/>
	      <span id="messageTip" hidden="true"></span>
   	</form>
</body>
</html>

 

 

后台Controller代码

//这种是使用传统的form表单提交的,即在前台页面上点击‘上传’按钮上传文件的形式,
//而且在form标签上必须指定enctype="multipart/form-data"
@RequestMapping(value = "getParamFromFile",method = RequestMethod.POST) @ResponseBody public Map<String, Object> getParamFromFile(@RequestParam("uploadFile") MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) { Map<String, Object> paramMap = new LinkedHashMap<String, Object>(); FileInputStream inputStream = null; try{ String filename = uploadFile.getName(); String originalFilename = uploadFile.getOriginalFilename(); System.out.println("FileName = " + filename); System.out.println("originalFilename = " + originalFilename); inputStream = (FileInputStream) uploadFile.getInputStream(); } catch (IOException e1) { paramMap.put("message", "上传文件错误"); return paramMap; } //String filePath = "E:\\work\\svn\\openeap\\code\\openeap\\src\\main\\webapp\\template\\北京市房屋租赁合同5.xml"; //paramMap = ImportFile.getParamFromFile(filePath); paramMap = ImportFile.getParamFromStream(inputStream); Iterator it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); System.out.println("参数 Key: " + e.getKey() + "; 参数 Value: " + e.getValue()); } System.out.println("生成的json为: " + JsonMapper.getInstance().toJson(paramMap)); return paramMap; } //jQuery form插件的使用 后台 @RequestMapping(value = "getParamFromFileForAjax",method = RequestMethod.POST) @ResponseBody public Map<String, Object> getParamFromFileForAjax(HttpServletRequest request,String fileName) { Map<String, Object> paramMap = new LinkedHashMap<String, Object>(); FileInputStream inputStream = null; //把Request强转成多部件请求对象 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; //根据文件名称获取文件对象 CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile(fileName); try{ String filename = commonsMultipartFile.getName(); String originalFilename = commonsMultipartFile.getOriginalFilename(); System.out.println("FileName = " + filename); System.out.println("originalFilename = " + originalFilename); inputStream = (FileInputStream) commonsMultipartFile.getInputStream(); } catch (IOException e1) { paramMap.put("message", "上传文件错误"); return paramMap; } //String filePath = "E:\\work\\svn\\openeap\\code\\openeap\\src\\main\\webapp\\template\\北京市房屋租赁合同5.xml"; //paramMap = ImportFile.getParamFromFile(filePath); paramMap = ImportFile.getParamFromStream(inputStream); Iterator it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); System.out.println("参数 Key: " + e.getKey() + "; 参数 Value: " + e.getValue()); } System.out.println("生成的json为: " + JsonMapper.getInstance().toJson(paramMap)); return paramMap; }

  

  异步上传文件有两种方式:

  参考的文章:

    http://www.cnblogs.com/zhuxiaojie/p/4783939.html#autoid-1-0-0

 

springmvc异步上传文件

标签:nal   Enctype   color   multipart   文件名   size   https   enc   err   

原文地址:http://www.cnblogs.com/move22/p/7246336.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!