springMVC实现文件上传:导入jar包 ----- 配置文件 ----- 提交表单 ----- controller层定义方法
一、导入jar包
jar包: com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.io-1.4.0.jar
二、xxx-servlet.xml配置文件
注意:主要配置id="multipartResolver"的bean标签,其他为基本配置(用的是注解)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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">
<mvc:annotation-driven/><!-- 驱动声明,2.0以上版本可以省略 -->
<context:component-scan base-package="com.hfxt.controller"></context:component-scan>
<!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 根据控制器返回的字符串拼接成jsp路径:/WEB-INF/page/xx.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"/><!-- 前缀 -->
<property name="suffix" value=".jsp"/><!-- 后缀 -->
</bean>
<!-- id的值必须为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1024000"></property>
</bean>
<mvc:resources location="/js/" mapping="/js/**"/><!-- js文件不提交给服务器 -->
</beans>
三、jsp页面表单提交
注意:<form>标签的 method="post" 和 enctype="multipart/form-data" 必不可少。
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>注册用户</title>
</head>
<body>
<form id="myForm" action="/spring_mvc_annotation/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username" /><br />
密码:<input type="password" name="password" /><br />
照片:<input type="file" name="photo"/><br />
<input type="submit" value="注册"/>
</form>
</body>
</html>
四、controller层定义方法
package com.hfxt.controller;
import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.hfxt.entity.User;
@Controller
@RequestMapping(value="/")
public class LoginController {
//注册页面(由于放在/web-inf/page目录下,所以定义该方法)
@RequestMapping(value="/register",method=RequestMethod.GET)
public String toRegister(){
return "register";
}
//文件上传
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(User user, HttpServletRequest httpServletRequest ,Model model){
System.out.println(user.getUsername());
try {
//转换成MultipartHttpServletRequest(继承了HttpServletRequest, MultipartRequest)
MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpServletRequest;
//用MultipartHttpServletRequest对象获取文件,CommonsMultipartFile实现了MultipartFile接口
CommonsMultipartFile cmFile = (CommonsMultipartFile) request.getFile("photo");//photo为表单的file的name
//获取文件的字节数字,方便后面的写操作
byte[] buf = cmFile.getBytes();
//获取原始文件的名称和后缀
String originalFilename = cmFile.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//文件后缀名
/*获取当前项目的真实路径,request.getSession().getServletContext() 获取的是Servlet容器对象,
相当于tomcat容器了。getRealPath("/") 获取实际路径,“/”指代项目根目录,
所以代码返回的是项目在容器中的实际发布运行的根路径*/
String path=request.getSession().getServletContext().getRealPath("/");
//设置要保存的文件名称:这里以当前时间到毫秒,还可以加随机数
Date date = new Date();
SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = sdf.format(date);//当前时间作为文件名
//构造url(根目录+upload文件夹+文件名+后缀),为了方便在数据库中存取
String url = path+"upload\\"+fileName+suffix;
System.out.println(url);
//创建upload文件夹
File dir = new File(path+"upload");
if(!dir.exists()){
dir.mkdir();//创建单级文件夹
}
//写文件
OutputStream os = new FileOutputStream(url);
os.write(buf);
os.close();
//判断上传成功与否(我这里比较简单,不够严谨)
File uploadFile = new File(url);
String message="";
if(!uploadFile.exists()){
message="上传失败!";
}else{
message="上传成功!";
}
//保存url,下载会用到
user.setUrl(URLEncoder.encode(url,"UTF-8"));//url编码,下载时需要解码
/*System.out.println("编码后url:"+user.getUrl());*/
model.addAttribute(user);
model.addAttribute("message",message);
} catch (Exception e) {
e.printStackTrace();
}
return "register_success";
}
}
一个基本的文件上传功能就实现了。
文件下载参照:http://blog.csdn.net/lpch0825/article/details/79410680