springMVC 文件上传 优化代码记录。

Controller<span style="white-space:pre">	</span>
 
 
package com.hmx.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


@Controller
//根目录
@RequestMapping("/file")
public class FileLoad {
	
	//优化版上传文件!
	@RequestMapping("/upload2")
	//RequestParam(jsp里的 name)   页面将所有信息都传送request表单,
	public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		//定义一个解析器 将springMVC上下文解析到
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//用解析器解析request里面的数据,并判断是否为Multipart类型的数据
		if(multipartResolver.isMultipart(request)){
			//request如果是Multipart类型的数据,将reques转化成MultipartHttpServletRequest类型 
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
			//拿文件  通过迭代器Iterator一个一个拿文件
			Iterator<String> iter = multiRequest.getFileNames();
			
			while(iter.hasNext()){
				//根据迭代器拿到的文件名称,传给file
				MultipartFile file = multiRequest.getFile((String)iter.next());
				//开始写文件
				if( file!=null){
					//上传后的文件名称	
					String fileName="上传后的文件  :"+file.getOriginalFilename();
					//上传后的文件位置
					String path="D:/"+fileName;
					
					File localFile = new File(path);
					//将上传文件(file)写到指点文件上(localFile)
					file.transferTo(localFile);
				}
			}
		}
		return "/success";
}
	
	
	@RequestMapping("/upload")
					//RequestParam(jsp里的 name)
	public String addFile(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException{
		System.out.println("文件上传      :"+file.getOriginalFilename());
		//上传文件,判断是否有文件
		if(!file.isEmpty()){
			try {
				//输出流        文件上传后保存的地方
				FileOutputStream os=new FileOutputStream("D:/"+file.getOriginalFilename());
				//输入流
				InputStream in=file.getInputStream();
				//读文件(一个一个字节读)
				int b=0;
				while((b=in.read())!=-1){
					os.write(b);
				}
				//关闭流
				os.flush();
				os.close();
				in.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
		return "/success";
	}
	

	
	@RequestMapping("/toload")
	public String toLoad(){
		
		return "upload";
	}
	
}

springMVC-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans	
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"  
	xmlns:mvc="http://www.springframework.org/schema/mvc"  
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
	
	<!-- 启动SpringMVC的注解功能-->
	<mvc:annotation-driven/>
	<!-- 加载包中的controller包(controller类所在的包名)    加载扫描注解包 -->
	<context:component-scan base-package="com.hmx.controller"/>
	
	<!-- 静态资源访问  (不拦截images文件夹下的文件)-->
	 <!-- 不拦截静态资源 <mvc:default-servlet-handler />  -->  					
	   <mvc:resources location="/images/" mapping="/images/**"/>
	   <mvc:resources location="/js/" mapping="/js/**"/>
	
	<!-- 多请求处理控制器 -->   
	   <bean id="paramMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">     
	<!-- 自己定义的配置标识action,当访问页地址栏输入访问名加上"?action=方法名"-->  
	   <property name="paramName" value="action">    
	   </property>     
	</bean> 
	
	<!-- 视图解析器  -->    
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">             
		<property name="prefix" value="/"></property>      
		<property name="suffix" value=".jsp"></property>  
	</bean>
	
	<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"></property>
		<property name="maxUploadSize" value="10485760000"></property>
		<property name="maxInMemorySize" value="40960"></property>
	</bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>springMVC4</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:/config/springMVC-servlet.xml</param-value>  
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

uoload.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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form name="userForm" action="/springMVC4/file/upload2" method="post" enctype="multipart/form-data">
		选择文件:<input type="file" name="file">
		<div><input type="submit" value="提交">
		</div>
	</form>
</body>
</html>


success.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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	上传文件成功!
</body>
</html>



你可能感兴趣的:(springMVC)