需要导入的依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
在spring中的applicationContext.xml中配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="5242440"></property>
</bean>
index.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>
<form action="${pageContext.request.contextPath }/file/upload.do"
method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file" width="120px"> <input
type="submit" value="上传">
</form>
<hr>
<form action="${pageContext.request.contextPath }/file/down.do"
method="get">
<input type="submit" value="下载">
</form>
</body>
</html>
${pageContext.request.contextPath }(提取所部署项目的名字的绝对路径)与 <%=request.getContextPath()%>等价,可以说是它的EL版本,意思就是取出部署的应用程序名或者是当前的项目名称 。
采用form表单提交的方式进行文件的上传与下载。/后面跟的是与controller中的方法连接的路径。
UploadTestServlet.java代码:
@Controller
@RequestMapping("file")
public class UploadTestServlet {
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File dir = new File(path,fileName);
if(!dir.exists()){
dir.mkdirs();
}
file.transferTo(dir);
return fileName;
}
@RequestMapping("/down")
public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{
String fileName = request.getSession().getServletContext().getRealPath("upload")+"/101.jpg";
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
String filename = "下载文件.jpg";
filename = URLEncoder.encode(filename,"UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
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();
}
}
String path = request.getSession().getServletContext().getRealPath("upload");
表示上传文件到的地址。
String fileName = request.getSession().getServletContext().getRealPath("upload") +"/101.jpg";表示在该路径下下载对应的101.jpg文件,也可以将它改为你想给别人下载的文件,接下来的是将文件以输入输出流的形式的代码。