springmvc上传下载文件
1、导入依赖;(jackson是因为在配置文件中添加了配置;)
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
2、在applicationContext.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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定包下的注解生效,由IOC统一管理-->
<context:component-scan base-package="com.zhang.controller"/>
<!--让springmvc不处理静态资源-->
<mvc:default-servlet-handler/>
<!-- JSON乱码问题配置 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--文件上传配置-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1-->
<property name="defaultEncoding" value="utf-8"/>
<!--上传文件大小上限,单位为字节(10485760=10M)-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
上传有两种方式;
//@RequestMapping("/file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
//批量上传CommonsMultipartFile则为数组即可。
@PostMapping("/upload")
public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request){
//获取文件名:file.getOriginalFilename()
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接返回首页!
if("".equals(uploadFileName)){
// return "redirect:/index.jsp";
return "请选择文件。";
}
System.out.println("上传文件名:" + uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:" + realPath);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = file.getInputStream();//文件输入流
outputStream = new FileOutputStream(new File(realPath,uploadFileName));//文件输出流
//读取写出
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1){
outputStream.write(buffer,0,len);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "上传成功";
// return "redirect:/index.jsp";
}
//采用file.Transto来保存上传的文件
@PostMapping("/upload2")
public String fileUpload2(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request){
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:" + realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
try {
file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
// return "redirect:/index.jsp";
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "";
// return "redirect:/index.jsp";
}
对应前端页面;
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload"/>
</form>
<form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload"/>
</form>
下载
@RequestMapping("/download")
public String downloads(HttpServletResponse response,HttpServletRequest request){
String path = request.getServletContext().getRealPath("/upload");
//下载哪个文件,写哪个名字
String filename ="L2Dwidget.min.js";
//1、设置response响应头
response.reset();//设置页面不缓存,清空buffer;
response.setCharacterEncoding("UTF-8");//字符编码
response.setContentType("multipart/form-data");//二进制传输数据
try{
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
File file = new File(path, filename);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(file);//文件输入流
outputStream = response.getOutputStream();//文件输出流
//读取写出
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1){
outputStream.write(buffer,0,len);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "下载成功。";
}