spring MVC异步上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/whd1985whd/article/details/80728327

spring NVC 异步上传的简单实例,原理省略,直接上代码。

1.html代码:

        

<form id="myform" enctype="multipart/form-data">
   					账号:<input type="text" name="username"/><br/><br/>
   					密码:<input type="text" name="password"/><br/><br/>
   					姓名:<input type="text" name="name"/><br/><br/>
   					年龄:<input type="text" name="age"/><br/><br/>
   					头像:<input type="file" name="file"/><br/><br/>
   					<input type="button" value="注册" onclick="zhuce()"/>
</form>

2.js代码:

    首先需要jquery1.8.3.min.js 和 jquery.form.js 

      

<script src="<%=basePath%>js/jquery1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
<script src="<%=basePath%>js/jquery.form.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
			function zhuce(){
				var form = new FormData(document.getElementById("myform"));
				$.ajax({
					type:'post',
					url:'test/zhuce',
					data:form,
					contentType: false,  
					processData:false,
					success: function(d){
						alert(d);
						window.location.href=window.location.href;
					}
				
				});
			
			}
	
</script>


3.spring MVC配置文件:

    

<bean id="multipartResolver"  
		        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
		        <!-- 默认编码 -->
		        <property name="defaultEncoding" value="utf-8" />  
		        <!-- 文件大小最大值 -->
		        <property name="maxUploadSize" value="10485760000" />  
		        <!-- 内存中的最大值 -->
		        <property name="maxInMemorySize" value="40960" />  
</bean>


4.服务端 java代码:

/**
  * @param response
  * @param student
  * @throws IOException 
  */
@RequestMapping("zhuce")
public void zhuce(HttpServletRequest request,HttpServletResponse response,Student student, @RequestParam("file") MultipartFile file) throws IOException{
		response.setCharacterEncoding("UTF-8");
		response.setContentType("html/text,charset=UTF-8");
		PrintWriter out=response.getWriter();
		/*判断账号是否存在*/
		List<Student> listStudent=service.findStudentByUserName(student.getUsername());
		if(!listStudent.isEmpty()){
			out.print("该账号已经存在");
			return;
		}
		
		/*图片上传*/
		
		//获取完整的文件名
		String name=file.getOriginalFilename();
		//获取最后一个'.'的下角标
		int i = name.lastIndexOf(".");	   
		//获取后缀。获取'.'后面的字符串 substring(某下角标):截取该下角标到最后的字符串
		String str =name.substring(i);
		//在截取后的字符串前加上时间戳,以保证字符串的唯一性。	                     
		String saveName= new Date().getTime()+"";
		//获取项目的绝对路径
		String path=request.getSession().getServletContext().getRealPath("/");
		//通过要上传的路径,来创建file对象
		File dir = new File(path + "img");
		//判断该文件夹是否存在,若不存在则建立文件夹
		if(!dir.exists()){		
		     dir.mkdirs();
		}
		//通过上传的路径和文件(图片名称),创建file对象。
		File files = new File(dir,saveName+str);
		try {
		     file.transferTo(files);//在指定路径,创建该图片文件	
		} catch (Exception e) {
		          e.printStackTrace();
		}
		
		
		/*存入数据库*/
		student.setTouxiang("img/"+saveName+str);
		int a=service.addStudent(student);
		if(a>0){
			out.print("注册成功");
		}else{
			out.print("注册失败");
		}
		
   }





猜你喜欢

转载自blog.csdn.net/whd1985whd/article/details/80728327
今日推荐