springmvc文件上传案例

1.引入jar包:commons-fileupload-1.2.2.jar,commons-io-2.0.1.jar(上传jar包),springmvc相关jar包等

2.student实体类

public class Student implements Serializable {

	private static final long serialVersionUID = -5304386891883937131L;

	private Integer stuId;

	private String stuName;

	private String stuPwd;

	private Integer stuAge;

	private MultipartFile[] files;

	public MultipartFile[] getFiles() {
		return files;
	}

	public void setFiles(MultipartFile[] files) {
		this.files = files;
	}

	public Integer getStuId() {
		return stuId;
	}

	public void setStuId(Integer stuId) {
		this.stuId = stuId;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public String getStuPwd() {
		return stuPwd;
	}

	public void setStuPwd(String stuPwd) {
		this.stuPwd = stuPwd;
	}

	public Integer getStuAge() {
		return stuAge;
	}

	public void setStuAge(Integer stuAge) {
		this.stuAge = stuAge;
	}

	@Override
	public String toString() {
		return "Student [stuId=" + stuId + ", stuName=" + stuName + ", stuPwd="
				+ stuPwd + ", stuAge=" + stuAge + "]";
	}
}

3.上传页面,上传参数的名称必须与实体类的属性名称相同,才能实现属性注入

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>     
     <form action="student/save.action" method="post" enctype="multipart/form-data">
     	姓名:<input type="text" name="stuName"><br/>
     	密码<input type="password" name="stuPwd"><br>
     	请选择文件:<br/><input type="file" name="files"><br/>
     	<input type="file" name="files"><br/>
     	<input type="submit" value="文件上传测试">    
     </form>    
  </body>
</html>

4.控制器

@Controller
@RequestMapping("/student")
public class StudentAction {
	
	public StudentAction(){
		System.out.println("---StudentAction构造方法被调用---");
	}

	@RequestMapping("/save")
	public String save(Student student) {
		System.out.println("save方法已注入student对象:"+student);
		MultipartFile[] files=student.getFiles();
		for(MultipartFile file:files){
			if(file.isEmpty()){
				System.out.println("文件为空");
			}else{
				System.out.println("文件不为空!");
				System.out.println("格式:" + file.getContentType());
				System.out.println("原名:" + file.getOriginalFilename());
				System.out.println("大小:" + file.getSize());
				System.out.println("表单控件的名称" + file.getName());
				try {
					FileUtils.copyInputStreamToFile(file.getInputStream(), new File("e:/testupload/"+file.getOriginalFilename()));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}
		}	
		System.out.println("---调用业务逻辑进行业务处理---");		
		//直接使用字符串,返回视图,进行结果展现等
		return "forward:/jsp/main.jsp";
	}
}

5.spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
	">
	
	<!-- 注解扫描配置 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<context:component-scan base-package="*"/>
	
	<!--文件上传使用, 配置multipartResolver,id名称为约定好的 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 配置文件(每次上传的所有文件总大小)大小,单位为b, 1024000表示1000kb  -->
		<property name="maxUploadSize" value="1024000" />		
	</bean>

</beans>

6.控制器处理后跳转页面 jsp/main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
  <head>
      <title>main.jsp</title>	
  </head>
  
  <body>
    /jsp/main.jsp页面
          student: ${requestScope.student}
  </body>
</html>

7.web.xml,配置前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
	<servlet>
		<servlet-name>mvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>
</web-app>

8.中文乱码处理,配置web.xml

<filter>
		<filter-name>encodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

9.优化

1)编写文件上传工具类

@Component(value="fileUploadUtils")  //普通的bean注入
public class FileUploadUtils {
	/*
	 * 注入字符串,#{}为spel语言,其中uploadProperties,是xml配置文件中注入properties文件的bean id,
	 *  path为properties文件的其中一个key ,也可以通过下边的set方法注入
	 */
	
	@Value("#{uploadProperties.path}") 
	private String path;
	//private String path="e:/testupload";
	
	//path也可以通过set方法注入
//	@Value("#{uploadProperties.path}") 
//	public void setPath(String path) {
//		this.path = path;
//	}	
	
	private String getExtName(MultipartFile file){
		return FilenameUtils.getExtension(file.getOriginalFilename());
	}

	private String createNewName(MultipartFile file){
		return UUID.randomUUID().toString()+"."+getExtName(file);
	}
	
	public String uploadFile(MultipartFile file){
		try {
			String newName=createNewName(file);
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,newName ));
			return newName;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);			
		}		
	}
}

2)修改StudentAction.java

@Controller
@RequestMapping(value="/student")
public class StudentAction {

	@Resource
	private ServletContext application;
	
	@Resource
	private FileUploadUtils fileUploadUtils;
	
	public StudentAction(){
		System.out.println("---StudentAction构造方法被调用---");
	}

	@RequestMapping(value="/save")
	public String save(Student student,Map<String, Student> paramMap) {
		System.out.println("save方法已注入student对象:"+student);
		MultipartFile[] files=student.getFiles();
		for(MultipartFile file:files){
			if(file.isEmpty()){
				System.out.println("文件为空");
			}else{
				System.out.println("文件不为空!");
			
				fileUploadUtils.uploadFile(file);
			}
		}	
		System.out.println("---调用业务逻辑进行业务处理---");		
		paramMap.put("student",student);		
		//直接使用字符串,返回视图,进行结果展现等
		return "forward:/jsp/main.jsp";
	}
}

3.添加upload.properties,文件上传存放目录,path在FileUploadUtils中有用到

path=e\:\\testdir\\upload\\

4.修改spring-mvc.xml,扫描配置文件

<!--PropertiesFactoryBean对properties文件可用 ,可以用来注入properties配置文件的信息 -->
	<bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="location" value="classpath:upload.properties"></property>
	</bean>









猜你喜欢

转载自blog.csdn.net/weixin_41762621/article/details/80982724