springmvc配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描注解 -->
<context:component-scan base-package="com.test.controller"></context:component-scan>
<!-- 注册驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 加载资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/img/" mapping="/img/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<!-- 配置视图解析器 -->
<bean id="viewResover" 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="maxUploadSize" value="2048"></property>
</bean>
<!-- 设置异常处理器 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>
</props>
</property>
</bean>
</beans>
controller
package com.test.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class Test {
@RequestMapping("download")
public void downLoad(String filename,HttpServletRequest req,HttpServletResponse resp) throws IOException {
resp.setHeader("Content-Disposition", "attachment;filename="+filename);
ServletOutputStream os = resp.getOutputStream();
String path = req.getServletContext().getRealPath("file");
File file =new File(path, "a.txt");
byte[] bs = FileUtils.readFileToByteArray(file);
os.write(bs);
os.flush();
}
@RequestMapping("upload")
public String upload(MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
String subfix = filename.substring(filename.lastIndexOf("."));
FileUtils.copyInputStreamToFile(file.getInputStream(), new File("D:/"+UUID.randomUUID()+subfix));
return "index";
}
}