效果:
需要的资源:
commons-fileupload-1.3.1.jar,commons-io-1.3.2.jar
步骤:
1:搭建SSM框架:
2:在配置文件springconfig.xml中添加配置
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880" />
<property name="maxInMemorySize" value="4096" />
</bean>
3:编写下载jsp文件:download.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载文件</title>
</head>
<body>
<h1>文件下载实例</h1>
<form action="${pageContext.request.contextPath}/download.action" method="get">
<input type="submit" value="下载">
</form>
</body>
</html>
4:编辑控制器:
/**
* 文件下载功能
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/download")
@ResponseBody
public String down(HttpServletRequest request,HttpServletResponse response) throws Exception{
//模拟文件,myfile.txt为需要下载的文件
String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt";
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//假如以中文名下载的话
String filename = "下载文件.txt";
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
return "login2";
}
5:运行,成功的话页面信息如下,点击下载看是否能正常下载: