springmvc的文件上传和下载案例
1.项目结构
2.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.yunhe.ssm</groupId>
<artifactId>ssmDemo5</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>ssmDemo5 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- 引入servletAPI解决编译servlet问题 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- 引入springmvc依赖包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- freemarker模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- jackson依赖包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- log4j依赖包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- 文件上传下载 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<finalName>ssmDemo5</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- JETTY服务器插件 -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.6.v20170531</version>
</plugin>
<!--tomcat服务器插件-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>8088</port>
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
<server>tomcat7</server>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--自己指定springmvc.xml文件的位置 默认会找 springmvc-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration monitorinterval="1800" status="off">
<properties>
<!-- 绝对路径【F://logs/sample】 -->
<property name="LOG_HOME">logs/sample</property>
</properties>
<!--先定义所有的appender -->
<appenders>
<!--这个输出控制台的配置 -->
<Console name="Console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
<ThresholdFilter level="trace" onMatch="ACCEPT"
onMismatch="DENY" />
<!--这个都知道是输出日志的格式 -->
<PatternLayout
pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" />
</Console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
<File name="log" fileName="${LOG_HOME}/test.log" append="false">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" />
</File>
<!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
<RollingFile name="RollingFile" fileName="${LOG_HOME}/app.log"
filePattern="${LOG_HOME}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout
pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n" />
<SizeBasedTriggeringPolicy size="50MB" />
</RollingFile>
</appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
<loggers>
<!--建立一个默认的root的logger -->
<root level="debug">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</root>
</loggers>
</configuration>
5.springmvc.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:p="http://www.springframework.org/schema/p"
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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!--读取资源文件-->
<context:property-placeholder location="classpath:system.properties"/>
<!--扫描指定包下的注解驱动-->
<context:component-scan base-package="cn.yunhe.controller"/>
<!--mvc注解驱动-->
<mvc:annotation-driven/>
<!--处理静态资源-->
<mvc:default-servlet-handler/>
<!--=================================================视 图 解 析 器=========================================================-->
<!-- JSP视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- FREEMARKER视图解析器 -->
<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".ftl" />
<property name="order" value="1"></property>
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="" />
<property name="freemarkerSettings">
<props>
<prop key="default_encoding">UTF-8</prop>
</props>
</property>
</bean>
<!-- 多部分文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的大小,单位为字节 -->
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<!-- 请求的编码格式 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上传文件的临时路径 -->
<property name="uploadTempDir" value="/fileUpload/temp"></property>
</bean>
</beans>
6.system.properties
7.Const.java
package cn.yunhe.controller;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2017/7/27.
*/
public class Const {
public static Map<String,String> fileMap =new HashMap<String,String>();
static{
fileMap.put("8e95d460-6ab0-4cfe-902b-8db4ee0843cc","人.png");
}
}
8.UpFileController.java
package cn.yunhe.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* Created by Administrator on 2017/7/26.
*/
@Controller
public class UpFileController {
private Logger logger= LogManager.getLogger(UpFileController.class);
@Value("${fileSavePath}")
private String fileSavaPath;
@RequestMapping("/")
public String upmenu(){
return "upfile";
}
@RequestMapping(value = "/upfile",method = RequestMethod.POST)
public String upfile(String username, MultipartFile[] userhand) {
logger.debug("username="+username+",userhand="+userhand);
for (MultipartFile mult:userhand){
String fileName= UUID.randomUUID().toString();
Const.fileMap.put(fileName,mult.getOriginalFilename());
try {
mult.transferTo(new File(fileSavaPath+fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
}
9.DownFileController.java
package cn.yunhe.controller;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* Created by Administrator on 2017/7/26.
*/
@Controller
public class DownFileController {
private Logger logger= LogManager.getLogger(DownFileController.class);
@Value("${fileSavePath}")
private String fileSavaPath;
@RequestMapping("/downfile")
public void downFile(String filename, HttpServletResponse resp){
logger.debug("fileSavaPath="+fileSavaPath);
resp.setContentType("application/octet-stream; charset=utf-8");
//设置文件名
String realOriginalFilename = Const.fileMap.get(filename);
String aa = null;
try {
aa = new String(realOriginalFilename.getBytes("utf-8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
resp.setHeader("Content-Disposition", "attachment; filename=" + aa);//以附件方式下载,防止浏览器直接打开
try {
IOUtils.copy(new FileInputStream(new File(fileSavaPath, filename)), resp.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}