1 导入jar
<dependencies>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
2 配置springmvc
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/page/" p:suffix=".jsp" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上传图片最大大小5M -->
<property name="maxUploadSize" value="10485760"></property>
</bean>
3 上传代码
@RequestMapping("upload")
public String upload(MultipartFile file,HttpServletRequest request)
{
String fileName = file.getOriginalFilename();
File dir = new File("e:/temp/",fileName);
if(!dir.exists()){
dir.mkdirs();
}
//MultipartFile自带的解析方法
try {
file.transferTo(dir);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// DispatcherServlet
return "index";
}
@RequestMapping("hello")
public String index(String page)
{
return "index";
}
4 下载代码
@RequestMapping("down")
public void 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();
}
5丶 jsp页面上传时注意给from加
method="post" enctype="multipart/form-data"
这两个关键
6丶 下载的时候需要注意有没有这个文件夹 和文件 没有的话就创建一个
并且把页面改成 method=“ get”